面试题答案
一键面试- 添加依赖:
在
build.gradle
文件中添加Mockk依赖:
testImplementation 'io.mockk:mockk:1.13.5'
- 定义网络请求接口: 假设我们有一个简单的网络请求接口:
interface ApiService {
suspend fun fetchData(): String
}
- 编写单元测试:
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.RelaxedMockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class ExampleUnitTest {
@RelaxedMockK
lateinit var apiService: ApiService
@BeforeEach
fun setUp() {
MockKAnnotations.init(this)
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testFetchData() = runTest {
val mockResponse = "Mocked data"
coEvery { apiService.fetchData() } returns mockResponse
val result = apiService.fetchData()
assert(result == mockResponse)
}
}
在上述代码中:
- 首先通过
@RelaxedMockK
注解创建了一个ApiService
的模拟对象。 @BeforeEach
注解的方法中通过MockKAnnotations.init(this)
初始化Mockk框架。- 在测试方法中,使用
coEvery
来定义当调用apiService.fetchData()
时返回我们预设的模拟数据mockResponse
。 - 最后调用
apiService.fetchData()
并断言返回结果与模拟数据一致。