android - 机器人 3 : Shadow custom class

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

我正在使用 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/

相关文章:

python - 如何在 pytest 中将单元测试和集成测试分开

android - 使用 Robolectric 检查调用的方法

.net - 测试设置中的 MsTest DeploymentItem OutputDirectory

groovy - Groovy 中没有参数的模拟静态方法

java - 与 NullPointerException 作斗争

android - 获取 FirebaseInstanceId : background sync failed: TIMEOUT error while trying to get an instance ID

android - 单击切换按钮时 TextInputLayout (TextInputEditText) NullpointerException

android - 加载大背景图像时内存不足

c# - 单元测试 Web App 时如何模拟应用程序路径

java - 调用模拟对象的方法时如何验证返回值