JUnit 5:如何在用 Kotlin 编写的测试中使用多个扩展?

aku*_*ubi 4 android junit4 kotlin junit5 mockk

我正在尝试将我的测试从 JUnit 4 迁移ViewModel到 JUnit 5,并结合使用 MockK。在 JUnit4 中,我在一个测试中使用了规则,即 RxJava2、LiveData 和 Coroutines 的规则,并且效果很好。我是这样使用它们的:

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)
    }
...
}
Run Code Online (Sandbox Code Playgroud)

在尝试迁移到 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)
    }
...
Run Code Online (Sandbox Code Playgroud)

但是,我收到一条错误,指出getMainLooper未模拟,这与在 JUnit4 中不使用 InstantTaskExecutorRule 时遇到的错误相同:

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
Run Code Online (Sandbox Code Playgroud)

在 Junit5 中使用多个扩展的正确方法是什么?

aku*_*ubi 6

@Extension我不应该使用 ,而是应该@ExtendWith以这种方式使用:

@ExtendWith(value = [InstantExecutorExtension::class, MainCoroutineExtension::class, RxSchedulerExtension::class])
Run Code Online (Sandbox Code Playgroud)

或者用更短的方式:

@ExtendWith(InstantExecutorExtension::class, MainCoroutineExtension::class, RxSchedulerExtension::class)
Run Code Online (Sandbox Code Playgroud)