kotlin +改装+协程+ androidTest

时间:2019-06-08 13:12:45

标签: 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) }
}

1 个答案:

答案 0 :(得分:1)

您可以通过Square使用MockWebServer库。

在测试源集中(src / test / resources)中创建一个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"
  }
]

然后您可以将测试编写为:


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
  }

}

不过,您必须问自己,您要测试的是什么?无需测试Retrofit的功能。您也不应该测试Moshi等其他知名库的功能。

这些测试最有效的目的是验证您为API响应创建的数据模型确实正确,并且您的解析器(在本例中为Moshi)可以正确地正确处理意外的值(例如null)。因此,重要的是,您选择的样本响应是来自API的实际响应,以便可以在测试中将数据模型针对测试中的真实数据进行验证,然后才能在应用中使用。