【问题标题】:How to test suspend function using MockK?如何使用 MockK 测试挂起功能?
【发布时间】:2021-10-31 00:12:13
【问题描述】:

我正在为我的 Datarepository 层编写一个单元测试,它只是调用一个接口。 我正在使用 Kotlin、协程和 MockK 进行单元测试。 在 MockK 中,我如何验证我是否已致电 apiServiceInterface.getDataFromApi() 并且只发生过一次? 我应该将代码放在 runBlocking 中吗?

这是我的代码:

单元测试

import com.example.breakingbad.api.ApiServiceInterface
import com.example.breakingbad.data.DataRepository
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import org.junit.Test

存储库

class DataRepositoryTest {
    @MockK
    private lateinit var apiServiceInterface: ApiServiceInterface

    @InjectMockKs
    private lateinit var dataRepository: DataRepository

    @Test
    fun getCharacters() {
            val respose = dataRepository.getCharacters()
            verify { apiServiceInterface.getDataFromApi() }
    }
}

    class DataRepository @Inject constructor(
    private val apiServiceInterface: ApiServiceInterface
) {
    suspend fun getCharacters(): Result<ArrayList<Character>> = kotlin.runCatching{
        apiServiceInterface.getDataFromApi()
    }
}

界面

interface ApiServiceInterface {
    @GET("api/characters")
    suspend fun getDataFromApi(): ArrayList<Character>
}

【问题讨论】:

    标签: android unit-testing kotlin mockito mockk


    【解决方案1】:

    是的,您应该将dataRepository.getCharacters() 调用放入runBlocking

    并且verify 应该替换为coVerify

    最后,测试应该是这样的:

    @Test
    fun getCharacters() {
        val respose = runBlocking { dataRepository.getCharacters() }
        
        coVerify { apiServiceInterface.getDataFromApi() }
    }
    

    另外,由于您想验证它只发生过一次,您需要使用 exactly 参数调用coVerify coVerify(exactly = 1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多