我需要模拟一些自定义类(为它创建一个影子)。 我已经阅读了 http://robolectric.org/custom-shadows/如何做到这一点。
所以,我有一些课:
public class MyClass {
public static int regularMethod() { return 1; }
}
我创建了一个影子:
@Implements(MyClass.class)
public class MyShadowClass {
@Implementation
public static int regularMethod() { return 2; }
}
然后我在测试类中设置了阴影:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, shadows={MyShadowClass.class})
public class MyTest {
@Test
public void testShadow() {
assertEquals(2, MyClass.regularMethod());
}
}
但是没有使用阴影。
java.lang.AssertionError:
Expected :2
Actual :1
如何使任何自定义阴影对 RobolectricGradleTestRunner 可见?
我已经试过了:
- http://www.codinguser.com/2015/06/how-to-create-shadow-classes-in-robolectric-3/
- https://github.com/jiahaoliuliu/RobolectricSample/blob/master/app-tests/src/main/java/com/jiahaoliuliu/robolectricsample/RobolectricGradleTestRunner.java
- Mock native method with a Robolectric Custom shadow class
但是我得到了各种编译错误,比如
InstrumentingClassLoaderConfig
未找到设置
未找到
如何在robolectric 3.0中正确使用自定义阴影?
最佳答案
自定义阴影应该避免,并且必须是最后的手段。仅当您不能在代码中进行太多重构而阻止您像本地方法调用一样运行测试时才应使用它。最好使用 powermock 或 mockito 模拟该类的对象或 spy ,而不是自定义阴影。如果是静态方法,则使用 powermock。
在我们的项目中,我们有一个具有一些本地方法的类,它是应用程序中随处使用的配置类。所以我们将本地方法移动到另一个类并隐藏它。那些 native 方法未能通过测试用例。
无论如何,这是在 robolectric 3.0 中自定义阴影的方法:
创建一个扩展 RobolectricGradleTestRunner 的自定义测试运行器:
public class CustomRobolectricTestRunner extends RobolectricGradleTestRunner {
public CustomRobolectricTestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
public InstrumentationConfiguration createClassLoaderConfig() {
InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
builder.addInstrumentedPackage("com.yourClassPackage");
return builder.build();
}
确保包中不包含您正在使用 robolectric 运行的任何测试用例。
关于android - 如何在 robolectric 3.0 中创建自定义阴影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31920865/