我正在为我的Datarepository层编写一个单元测试,它只是调用一个接口。我使用Kotlin、协程和MockK进行单元测试。在MockK中,我如何验证我调用了apiServiceInterface.getDataFromApi()并且只调用了一次?我应该把代码放在runBlocking中吗?
这是我的代码:
UnitTest
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>
}发布于 2021-11-28 12:12:28
是的,您应该将dataRepository.getCharacters()调用放在一个runBlocking中。
并且应该将coVerify替换为verify。
最后,测试应该是这样的:
@Test
fun getCharacters() {
val respose = runBlocking { dataRepository.getCharacters() }
coVerify { apiServiceInterface.getDataFromApi() }
}此外,由于您希望验证它只发生过一次,因此需要使用确切的参数coVerify(exactly = 1)调用coVerify
https://stackoverflow.com/questions/69014652
复制相似问题