How to mock Retrofit API responses for testing in Kotlin Android
How to mock Retrofit API responses for testing in Kotlin Android.
Here's a detailed step-by-step tutorial on how to mock Retrofit API responses for testing in Kotlin Android.
Step 1: Set up Retrofit
First, you need to set up Retrofit in your Android project. Add the Retrofit dependency to your build.gradle
file:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
Create an interface that defines your API endpoints. For example:
interface ApiService {
@GET("users/{username}")
suspend fun getUser(@Path("username") username: String): User
}
Create a Retrofit instance and initialize it with the base URL and a converter factory. For example:
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
Step 2: Set up MockWebServer
MockWebServer is a library that allows you to mock HTTP responses for testing. Add the MockWebServer dependency to your build.gradle
file:
debugImplementation 'com.squareup.okhttp3:mockwebserver:4.9.1'
Create an instance of MockWebServer in your test class:
val server = MockWebServer()
Step 3: Enqueue Mock Responses
In your test, before making the API request, enqueue the mock response using MockWebServer. For example:
val mockResponse = MockResponse()
.setResponseCode(200)
.setBody("{ \"name\": \"John Doe\" }")
server.enqueue(mockResponse)
Step 4: Start MockWebServer
Start the MockWebServer before making the API request:
server.start()
Get the base URL of the MockWebServer and replace the base URL in your Retrofit instance:
val mockUrl = server.url("/")
val mockBaseUrl = mockUrl.toString()
retrofit = retrofit.newBuilder()
.baseUrl(mockBaseUrl)
.build()
Step 5: Make the API Request
Make the API request using the Retrofit instance:
val response = apiService.getUser("john")
Step 6: Verify the Mock Response
Verify that the response received is the same as the mock response:
assertEquals(200, response.code)
assertEquals("{ \"name\": \"John Doe\" }", response.body)
Step 7: Stop MockWebServer
Stop the MockWebServer after the test:
server.shutdown()
That's it! You have successfully mocked Retrofit API responses for testing in Kotlin Android. This allows you to test your app's network requests without making actual API calls.