android - 如何在 robolectric 3.0 中创建自定义阴影?

标签 android testing robolectric shadows

我需要模拟一些自定义类(为它创建一个影子)。 我已经阅读了 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 可见?

我已经试过了:

  1. http://www.codinguser.com/2015/06/how-to-create-shadow-classes-in-robolectric-3/
  2. https://github.com/jiahaoliuliu/RobolectricSample/blob/master/app-tests/src/main/java/com/jiahaoliuliu/robolectricsample/RobolectricGradleTestRunner.java
  3. 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/

相关文章:

java - Resources$NotFoundException 调用 Robolectric.buildActivity() 时

Android Studio "0 test classes found in package"当 "rerun failed tests"

android - 捕获在自定义 View (布局)中选择的上下文菜单项的方法是什么?

java - NestedScrollView 未显示在 AlertDialog 中

android - 在 c 文件名的开头和结尾之后使用双下划线 ( __ ) 的目的是什么?

javascript - Angular - 单元测试按键

swift - 测试 NSURLSession "resume cannot be sent to abstract instance of class NSURLSessionDataTask"

python - Django 测试 - 当我使用查询集获取它时无法保存我的对象

android - 找不到兼容的并排 NDK 版本 React Native

android - 如何从 Paging 3 测试 PagingData