Where is log output written to when using Robolectric + Roboguice?

后端 未结 6 1664
被撕碎了的回忆
被撕碎了的回忆 2021-02-01 13:10

I\'m using Robolectric to test Android. I\'m running my tests via maven, e.g.

mvn -Dtest=LogTest test

If I have code that writes to the logs,

6条回答
  •  情深已故
    2021-02-01 13:32

    The solution that worked out best for me (or at all) was to initialize a replacement injected implementation (during testing only) of RoboGuice's Ln.Print class to do System.out printing instead of Android's Log printing, given I was actually using Robolectric to avoid having to depend on the Android subsystem to run my tests in the first place.

    From Ln.java:

    public class Ln  {
    ...
    
    /**
     * print is initially set to Print(), then replaced by guice during
     * static injection pass.  This allows overriding where the log message is delivered to.
     */
    @Inject protected static Print print = new Print();
    

    So basically:

    public class TestModule extends AbstractModule {
    
        @Override
        protected void configure() {
            bind(Ln.Print.class).to(TestLogPrint.class);
        }
    
    }
    

    and:

    public class TestLogPrint extends Print {
    
        public int println(int priority, String msg ) {
    
            System.out.println(
                String.format(
                    "%s%s", 
                    getScope(4), 
                    msg
                )
            );
    
            return 0;
        }
    
        protected static String getScope(int skipDepth) {
            final StackTraceElement trace = Thread.currentThread().getStackTrace()[skipDepth];
            return String.format("%s | %s.%s | ", new Date(), trace.getFileName().replace(".java", ""), trace.getMethodName());
        }
    }
    

    That of course assuming the standard Robolectric init to hook the module up with RoboGuice:

    @Before
    public void setUp() throws Exception {
    
        Module roboGuiceModule = RoboGuice.newDefaultRoboModule(Robolectric.application);
        Module productionModule = Modules.override(roboGuiceModule).with(new CustomRoboModule());
        Module testModule = Modules.override(productionModule).with(new TestModule());
    
        RoboGuice.setBaseApplicationInjector(Robolectric.application, RoboGuice.DEFAULT_STAGE, testModule);
        RoboGuice.injectMembers(Robolectric.application, this);
    
    }
    

提交回复
热议问题