如何解决JUnit 5:如何在用 Kotlin 编写的测试中使用多个扩展?
我正在尝试将 viewmodel
的测试从 JUnit 4 迁移到 JUnit 5,并结合使用 MockK。在 JUnit4 中,我在一个测试中使用了规则——即 RxJava2、LiveData 和协程的规则,并且效果很好。以下是我如何使用它们:
class CollectionListviewmodelTest {
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@get:Rule
val taskExecutorRule = InstantTaskExecutorRule()
@get:Rule
val rxSchedulerRule = RxSchedulerRule()
@ExperimentalCoroutinesApi
@get:Rule
val coroutineRule = MainCoroutineRule()
@Mock
lateinit var getAllCollectionsUseCase: GetAllCollectionsUseCase
private lateinit var SUT: CollectionListviewmodel
@Before
fun setUp() {
SUT = CollectionListviewmodel(getAllCollectionsUseCase)
}
...
}
在尝试迁移到 junit5 时,我了解到规则现在是扩展,在搜索之后我拼凑了我以前使用的规则的替代品,并且用 MockK 替换了 Mockito,我尝试在这个中用扩展替换规则方式:
@ExperimentalCoroutinesApi
@Extensions(
ExtendWith(InstantExecutorExtension::class),ExtendWith(MainCoroutineExtension::class),ExtendWith(RxSchedulerExtension::class)
)
class CollectionListviewmodelTest {
@MockK
lateinit var getAllCollectionsUseCase: GetAllCollectionsUseCase
private lateinit var SUT: CollectionListviewmodel
@Before
fun setUp() {
MockKAnnotations.init(this)
SUT = CollectionListviewmodel(getAllCollectionsUseCase)
}
...
但是,我收到一条错误消息,指出未模拟 getMainLooper
,这与在 JUnit4 中不使用 InstantTaskExecutorRule 时遇到的错误相同:
java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
解决方法
我应该以这种方式使用 @Extension
而不是使用 @ExtendWith
:
@ExtendWith(value = [InstantExecutorExtension::class,MainCoroutineExtension::class,RxSchedulerExtension::class])
或者以更短的方式:
@ExtendWith(InstantExecutorExtension::class,RxSchedulerExtension::class)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。