【问题标题】:Robolectric 3: Shadow custom classRobolectric 3:影子自定义类
【发布时间】:2015-12-21 09:40:11
【问题描述】:

我正在使用 Robolectric 3,我正在尝试像这样隐藏自定义类:

public class Yakir {

    public int foo() {
        return 1;
    }


}

@Implements(Yakir.class)
public class TestYakir {

    @Implementation
    public int foo() {
        return 2;
    }


}

我已经阅读了 Robolectric 阴影 SDK 类和自定义类的其他答案和帖子,我需要做一些特别的事情像这样:

公共类 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: 预期:2 实际:1

谢谢!

【问题讨论】:

    标签: android unit-testing mocking robolectric robolectric-gradle-plugin


    【解决方案1】:

    因此,在网络上进行了更多挖掘之后,我找到了一个适合我的简单解决方案。

    你需要做的就是重写类中扩展的方法

    RobolectricGradleTestRunner

    方法是:

    @Override
    public InstrumentationConfiguration createClassLoaderConfig() {
        InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
        builder.addInstrumentedClass(YourCustomShadowClass.class.getName());
        return builder.build();    }
    

    就是这样!测试顺利通过:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多