【发布时间】: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