Skip to content

Testing Library ‐ MockWebServer

Devrath edited this page Oct 25, 2023 · 4 revisions

github-header-image

About the library

Github

click here to access

How it is useful

  • It is like an offline web server that we can use to write tests.
  • When we are testing the app, We do not want to interact with real-api and use the real web server.
  • Sometimes the API's take a longer time to respond and we want to execute our tests fast.
  • If there is no internet connection then the test cases will fail, so this should not happen and the test cases should fail only if any issues in the source code.

Testing a network API

  • Using a MockWebServer we can test retrofit API's because. We can mock real responses by passing to them and check what is the behaviour.
  • It's very handy to test API-specific functionality.

Code sample

class ProductRepositoryImplTest {

    // Define the SUT: System under test :-> In our case it is repository
    private lateinit var sut : ProductRepositoryImpl

    private lateinit var api: ProductApi
    private lateinit var logger: AnalyticsLogger

    private lateinit var mockWebServer: MockWebServer


    @BeforeEach
    fun setup(){
        mockWebServer = MockWebServer()
        // Build the retroft instance and pass a mockServer instead of real api
        api = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(mockWebServer.url("/"))
            .build()
            .create()

        logger = mockk(relaxed = true)
        sut = ProductRepositoryImpl(productApi = api, analyticsLogger = logger)
    }

    @Test
    fun `Response error, Exception logged - Using Mock server`() = runBlocking {
        // We can enqueue the
        mockWebServer.enqueue(
            MockResponse().setResponseCode(404)
        )

        // make the call to the API
        val result = sut.purchaseProducts(listOf())

        assertThat(result.isFailure).isEqualTo(true)
    }
}