-
Notifications
You must be signed in to change notification settings - Fork 0
Testing Library β MockWebServer
Devrath edited this page Oct 25, 2023
·
4 revisions
- 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.
- 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.
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)
}
}