【问题标题】:Run all coroutines class test fail运行所有协程类测试失败
【发布时间】:2019-07-06 23:42:19
【问题描述】:

我正在测试我的演示者课程和所有测试工作。但是当我尝试运行我的测试类时,所有协程测试都失败了。

我正在尝试重置我的调度并清理我的范围。

private val dispatcher = TestCoroutineDispatcher()

private val testScope = TestCoroutineScope(dispatcher)

@Before
fun setUp() {
    Dispatchers.setMain(dispatcher)
    products = ProductsMotherObject.createEmptyModel()
    getProductsUseCase = GetProductsUseCase(productsRepository)
    updateProductsUseCase = UpdateProductsUseCase(productsRepository)
    presenter = HomePresenter(view, getProductsUseCase, updateProductsUseCase, products)
}

@After
fun after() {
    Dispatchers.resetMain()
    testScope.cleanupTestCoroutines()
}

这是我的测试示例

@Test
fun `should configure recyclerview if response is success`() = testScope.runBlockingTest {
    //Given
    `when`(productsRepository.getProductsFromApi()).thenReturn(mutableMapOf())

    //when
    presenter.fetchProducts()

    //then
    verify(view).hideLoading()
    verify(view).setUpRecyclerView(products.values.toMutableList())
} 

我的测试中只有一个错误,但每个测试在单独运行时都有效

【问题讨论】:

    标签: android unit-testing kotlin kotlin-coroutines


    【解决方案1】:

    解决了。我找到了this incredible post

    我做了什么:

    我在没有构造函数的情况下实现了调度程序。

        private val testDispatcher = TestCoroutineDispatcher()
    

    你必须设置@Before函数

    @Before
    fun setUp() {
        Dispatchers.setMain(testDispatcher)
    }
    

    并在测试后重置。

    @After
    fun after() {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
    

    最后,实现协程的每个测试都必须在 MainScope 上启动。

    @Test
    fun `should configure recyclerview if response is success`() = testDispatcher.runBlockingTest {
        MainScope().launch {
            //Given
            `when`(productsRepository.getProductsFromApi()).thenReturn(mutableMapOf())
    
            //when
            presenter.fetchProducts()
    
            //then
            verify(view).hideLoading()
            verify(view).setUpRecyclerView(products.values.toMutableList())
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 1970-01-01
      • 2015-02-19
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多