对我(或根本)最有效的解决方案是初始化 RoboGuice 的 Ln.Print 类的替换注入实现(仅在测试期间)以进行 System.out 打印而不是 Android 的日志打印,因为我实际上使用 Robolectric避免首先依赖 Android 子系统来运行我的测试。
从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();
所以基本上:
public class TestModule extends AbstractModule {
@Override
protected void configure() {
bind(Ln.Print.class).to(TestLogPrint.class);
}
}
和:
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());
}
}
当然,假设标准 Robolectric init 将模块与 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);
}