Skip to content

Instantly share code, notes, and snippets.

@faruktoptas
Created February 2, 2023 19:03
Show Gist options
  • Save faruktoptas/5934f2857d11129a37d0b778eeff05ff to your computer and use it in GitHub Desktop.
Save faruktoptas/5934f2857d11129a37d0b778eeff05ff to your computer and use it in GitHub Desktop.
Test Retrofit with mock web server
// testImplementation "com.squareup.okhttp3:mockwebserver:4.7.2"
class RetrofitTest {
@get:Rule
private val server = MockWebServer().apply { dispatcher = MockDispatcher() }
private lateinit var api: Api
@Before
fun setup() {
api = Retrofit.Builder()
.baseUrl(server.url("/").toString())
.client(OkHttpClient.Builder().build())
.addConverterFactory(GsonConverterFactory.create(Gson()))
.build()
.create(Api::class.java)
}
@Test
fun `test success response`() {
runBlocking {
val response = api.login(LoginRequest("user", "pass"))
Assert.assertEquals(true, response.isSuccessful)
Assert.assertEquals("token", response.body()?.token)
}
}
@Test
fun `test fail response`() {
runBlocking {
val response = api.register(LoginRequest("user", "pass"))
Assert.assertEquals(false, response.isSuccessful)
Assert.assertEquals(null, response.body()?.token)
Assert.assertEquals("{\"errorMessage\":\"failed\"}", response.errorBody()?.string())
}
}
}
class MockDispatcher : QueueDispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
return when (request.path) {
"/login" -> MockResponse()
.setResponseCode(200)
.setBody("{\"token\":\"token\"}")
else -> MockResponse()
.setResponseCode(412)
.setBody("{\"errorMessage\":\"failed\"}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment