我正在使用 Robolectric 3,我正在尝试像这样隐藏自定义类:
public class Yakir {
public int foo() {
return 1;
}
}
@Implements(Yakir.class)
public class TestYakir {
@Implementation
public int foo() {
return 2;
}
}
而且我已经阅读了 Robolectric 阴影 SDK 类和自定义类的其他答案和帖子,我需要做一些特别的事情,如下所示:
公共(public)类 RoboServiceRunner 扩展 RobolectricGradleTestRunner {
public RoboServiceRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
public Config getConfig(Method method) {
Config config = super.getConfig(method);
config.shadows();
return config;
}
@Override
protected ShadowMap createShadowMap(){
ShadowMap shadowMap = super.createShadowMap();
shadowMap = shadowMap.newBuilder().addShadowClass(ServiceTest.TestYakir.class).build();
return shadowMap;
}
}
所以您在这里看到的是将新类添加到 shadowMap 的代码。 我也知道 Shadows类,但我找不到如何处理它。
所以这个测试的输出:
@RunWith(RoboServiceRunner.class)
@Config(constants = BuildConfig.class, shadows = {ServiceTest.TestYakir.class})
public class ServiceTest {
@Test
@Config(constants = BuildConfig.class, shadows = {ServiceTest.TestYakir.class})
public void testService() {
assertEquals(2, new Yakir().foo());
}
是:
junit.framework.AssertionFailedError: Expected :2 Actual :1
谢谢!
最佳答案
因此,在对网络进行更多挖掘之后,我找到了一个适合我的简单解决方案。
所有你需要做的就是重写类中的一个方法来扩展
RobolectricGradleTestRunner
方法是:
@Override
public InstrumentationConfiguration createClassLoaderConfig() {
InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
builder.addInstrumentedClass(YourCustomShadowClass.class.getName());
return builder.build(); }
就是这样!测试顺利通过 :)
关于android - 机器人 3 : Shadow custom class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392661/