无法连续运行2个测试(希望但未调用实际上,此模拟的交互为零)

时间:2018-12-16 01:46:48

标签: android mocking mockito viewmodel

这里实际上有几个类似的问题,但是我尝试了所有建议,仍然面临着这个问题。

Wanted but not invoked:
observer.onChanged(<Repo matcher>);
-> at xxx.RepoViewModelTest.testRepoList(RepoViewModelTest.kt:51)
Actually, there were zero interactions with this mock.

class RepoViewModelTest {
    @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule()
    @Mock private lateinit var observer: Observer<DataWrapper<List<Repo>>>
    @Mock private lateinit var repoRepository: RepoRepository
    private lateinit var repoViewModel: RepoViewModel

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        repoViewModel = RepoViewModel(RepoUseCase(repoRepository))
    }

    @Test
    fun testError() {
        `when`(repoRepository.getRepos("mine"))
            .thenReturn(Observable.error(Exception("No internet")))
        repoViewModel.observeRepos().observeForever(observer)
        repoViewModel.getRepos("mine")    
        verify(observer).onChanged(
            argThat(RepoMatcher(DataWrapper(Exception("No internet")))))
    }

    @Test
    fun testRepoList() {
        val listIn = listOf(Repo("Repo1"), Repo("Repo2"))
        `when`(repoRepository.getRepos("mine"))
            .thenReturn(Observable.just(listIn))
        repoViewModel.observeRepos().observeForever(observer)
        repoViewModel.getRepos("mine")
        val listOut = listOf(Repo("Repo1"), Repo("Repo2"))
        verify(observer)
            .onChanged(argThat(RepoMatcher(DataWrapper(listOut))))
    }
}

我可以单独运行每个测试,但不能运行整个套件。 我试图在每次测试后重置模拟,为每个测试创建一个观察者,或实例化每个测试中的每个模拟对象,没有骰子。

在Android Studio 3.2.1中的app / xxx / test下运行测试

mockito 2.8.47

java 1.8.0_191

1 个答案:

答案 0 :(得分:0)

可能您需要这样的东西

@BeforeClass
public static void setupClass() {
    RxAndroidPlugins.setInitMainThreadSchedulerHandler(__ -> Schedulers.trampoline());
}