Android Retrofit Unit Test with MockServer

Retrofit Unit Test

Retrofit is HTTP Client. One of annoying test is Network API test.

To test this, we need to prepare server? Oh, it’s not realistic. We want to check API and response and handle response in Mobile App codes. That’s it.

Okhttp MockWebServer has solution of goals to test as Unit Test (Not Android Test)

It’s great!

Preparation

We just need to add following dependencies into test

build.gradle

testImplementation("com.squareup.okhttp3:mockwebserver:4.5.0")

O.K. It’s ready to start

Test Sample

In this time, I did test for last blog entry (Android kotlin Retrofit).

3 API both GET and POST covered. (If you know more details please check above entry)

Let’s do it!

ApiService.kt

class APIServiceTest {

    private var mockWebServer = MockWebServer()

    private lateinit var apiService : NetworkService

    @Before
    fun setup() {
        mockWebServer.start()

        apiService = Retrofit.Builder()
            .baseUrl(mockWebServer.url("/"))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(NetworkService::class.java)
    }

    @Test
    fun testGetUser() {
        val response = MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_OK)
            .setBody("{\"id\":\"111111\", \"name\":\"Takeshi\",\"age\":18}")

        mockWebServer.enqueue(response)

        val user = apiService.getUser("test").execute()
        Assert.assertNotNull(user)
        Assert.assertEquals("Takeshi", user.body()?.name)
        Assert.assertEquals(18, user.body()?.age)
        Assert.assertEquals("111111", user.body()?.id)
    }

    @Test
    fun testGetUserList() {
        val response = MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_OK)
            .setBody("[{\"id\":\"111111\", \"name\":\"Takeshi\",\"age\":18}, {\"id\":\"222222\", \"name\":\"Kasumi\",\"age\":18}]")

        mockWebServer.enqueue(response)

        val users = apiService.getList().execute()

        Assert.assertNotNull(users)
        Assert.assertEquals(2, users.body()?.size)
        Assert.assertEquals("Kasumi", users.body()?.get(1)?.name)
    }

    @Test
    fun testPost() {
        val response = MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_OK)
            .setBody("{\"success\":true}")

        mockWebServer.enqueue(response)

        val success = apiService.post("abc").execute()

        Assert.assertNotNull(success)
        Assert.assertEquals(true, success.body()?.success)
    }

    @After
    fun tearDown() {
        mockWebServer.shutdown()
    }
}
Android
スポンサーリンク
Professional Programmer2

コメント