关闭

在单元测试,集成测试与功能测试中模拟依赖

发表于:2016-5-27 10:19

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:lovexiaov    来源:51Testing软件测试网采编

  然后通过自定义RobolectricGradleTestRunner类使用该类。
  自定义带有定制化 application 类的 Robolectric 测试执行器
public class IntegrationRobolectricTestRunner extends RobolectricGradleTestRunner {
// This value should be changed as soon as Robolectric will support newer api.
private static final int SDK_EMULATE_LEVEL = 21;
public IntegrationRobolectricTestRunner(@NonNull Class<?> clazz) throws Exception {
super(clazz);
}
@Override
public Config getConfig(@NonNull Method method) {
final Config defaultConfig = super.getConfig(method);
return new Config.Implementation(
new int[]{SDK_EMULATE_LEVEL},
defaultConfig.manifest(),
defaultConfig.qualifiers(),
defaultConfig.packageName(),
defaultConfig.resourceDir(),
defaultConfig.assetDir(),
defaultConfig.shadows(),
MyIntegrationTestApp.class, // Here is the trick, we change application class to one with mocks.
defaultConfig.libraries(),
defaultConfig.constants() == Void.class ? BuildConfig.class : defaultConfig.constants()
);
}
}
  如何在 Instrumentation 测试中使用 Dagger 2 模拟并注入依赖?
  Google 的那帮兄弟建议使用 flavors,但我并不推荐使用它。因为 flavors 越多,构建应用花费的时间越长,你也会越不喜欢 Gradle 以及整个构建过程。如果可以避免,尽量不要使用 flavors。
  主要思路:与 Roboletric 测试相似——通过修改Application类来实现,不过这次是针对 Instrumentation 测试。
  为了实现此方法,你需要自定义 Instrumentation 测试执行器,并将它们添加到build.gradle中。
public class CustomInstrumentationTestRunner extends AndroidJUnitRunner {
@Override
@NonNull
public Application newApplication(@NonNull ClassLoader cl,
@NonNull String className,
@NonNull Context context)
throws InstantiationException,
IllegalAccessException,
ClassNotFoundException {
return Instrumentation.newApplication(CustomApp.class, context);
}
}
  将该类添加到build.gradle中:
android {
defaultConfig {
testInstrumentationRunner 'a.b.c.CustomInstrumentationTestRunner'
}
}
  代码示例:我已经将内容更新到 #qualitymatters app中,并做了分析,展示了在单元测试,集成测试和功能测试中模拟依赖的方式。 因为我们在测试真正应用时需要分析,但在实验中却不想分析!也许你已经注意到了,我们没有添加 flavors。
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号