kotlin - 如何将规则应用于 AndroidJUnitRunner 中的所有测试用例?
问题描述
我正在尝试在由特定跑步者运行的所有测试用例中应用 TestWatcher 作为规则。
元数据收集器:
class MetadataCollector : TestWatcher() { ... }
测试运行者:
class TestRunner : AndroidJUnitRunner() {
override fun onCreate(arguments: Bundle?) {
super.onCreate(arguments)
}
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
return super.newApplication(cl, TestApplication::class.java.name, context)
}
}
我所有的测试类目前都需要MetadataCollector()
初始化为规则:
测试类:
@JvmField @Rule val collector = MetadataCollector()
有没有办法可以从运行器自动为每个测试用例创建此规则的实例?理想情况下,这是为了避免@Rule
在每个单独的测试类中重复这个创建。
不幸的是,我现在被JUnit 4困住了。:(
解决方案
有一种更好的方法可以做到这一点,将 RunListener 的一个实例注入到您的测试运行器中。在您的 gradle 配置中,您需要:
defaultConfig.testInstrumentationRunner = "com.mypackage.MyTestRunnerClassName"
defaultConfig.testInstrumentationRunnerArgument("listener", "com.mypackage.MyRunListenerClassName")
并且在代码中,创建一个RunListenerClassName来实现对应的hook
class MyRunListener : RunListener() {
// impl
}
推荐阅读
- javascript - 如何编码从相机/网络摄像头录制视频,然后在 JavaScript 中上传
- azure - 使用 Terraform 提供程序将成员添加到预定义的 Azure AD 组
- python - 如何从带有单词的文件中列出列表?
- api - #linkedin 分享见解返回“权限不足”错误“状态 403”
- php - 如果数据库中不存在数据,如何显示所有月份名称
- c# - 视图模型上的 Xamarin 绑定属性:无法识别视图模型
- vue.js - 如何更改 vue.js 应用程序的名称
- javascript - 如何在 Visual Studio Code 中显示“console.log”输出?
- javascript - 来自两个 li 元素的逗号分隔列表
- javascript - 如何在 Vue.js 的编辑文件输入中赋予文件值?