Sam*_*man 2 android android-testing android-jetpack
如何androidTest为样品retrofit请求创建?
样本
data class TestDataClass(
val id: String,
val employee_name: String,
val employee_salary: String,
val employee_age: String,
val profile_image: String)
enum class NetworkState { LOADING, ERROR, DONE }
private const val BASE_URL = "http://dummy.restapiexample.com/api/v1/"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
interface TestApiService {
@GET("employees")
fun getPropertiesAsync():
Deferred<List<TestDataClass>>
}
object TestApi {
val retrofitTest : TestApiService by lazy { retrofit.create(TestApiService::class.java) }
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Square的MockWebServer库。
resources在您的测试源集 (src/test/resources) 中创建一个,并将包含来自您的 API 的示例响应的 JSON 文件放入其中。假设它看起来像这样:
src/test/resources/sample_response.json
[
{
"id": "1",
"employee_name": "John Doe",
"employee_salary": "60000",
"employee_age": 37,
"profile_image": "https://dummy.sample-image.com/johndoe"
}
]
Run Code Online (Sandbox Code Playgroud)
然后,您可以将测试编写为:
class ApiTest {
private lateinit var server: MockWebServer
private lateinit var retrofit: Retrofit
private lateinit var service: TestApiService
@Before
fun setup() {
server = MockWebServer()
retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(get<Moshi>()))
.addCallAdapterFactory(get<CoroutinesNetworkResponseAdapterFactory>())
.baseUrl(mockWebServer.url("/"))
.build()
service = retrofit.create(TestApi::class.java)
}
@After
fun teardown() {
server.close()
}
@Test
fun simpleTest() = runBlocking<Unit> {
val sampleResponse = this::class.java.getResource("/sample_response.json").readText()
server.enqueue(
MockResponse()
.setBody(sampleResponse)
)
val response = service.getPropertiesAsync().await()
assertTrue(1, response.size)
assertTrue(response[0].employee_name = "John Doe"
// Make as many assertions as you like
}
}
Run Code Online (Sandbox Code Playgroud)
但是,您必须问自己,您要测试的究竟是什么?无需测试 Retrofit 的功能。您也不应该测试其他知名库(如 Moshi)的功能。
这些测试最适合用于验证您为 API 响应创建的数据模型确实正确,并且您的解析器(在本例中为 Moshi)可以正确地正确处理意外值(例如 null)。因此,重要的是您选择的示例响应是来自 API 的实际响应,以便您的数据模型可以在应用程序中使用之前在测试中针对真实数据进行验证。
| 归档时间: |
|
| 查看次数: |
1035 次 |
| 最近记录: |