How to mock a Retrofit Response

Viewed 1188

I'm trying to mock a Retrofit Response when it isn't successful.

interface ServiceInterface {
@POST("auth/login")
suspend fun loginRequest(@Body loginInformation: LoginInformation) : Response<LoginResponse>}

I made an onSuccess test and it worked, but I don't know how to mock a Response when it isn't successful

@Test
fun onCallSuccess() = runBlocking {
    val response = Response.success(LoginResponse(status = "OK", token = "TOKEN"))
    coEvery {
        serviceMock.loginRequest(any())
    } returns response

    loginRepository.doLogin("", "")

    coVerify {
        serviceMock.loginRequest(any())
    }

    assertEquals(LoginResponse(status = "OK", token = "TOKEN"), loginRepository.doLogin("",""))
}
1 Answers

From the retrofit documentation:

public static <T> Response<T> error(int code, okhttp3.ResponseBody body)

Create a synthetic error response with an HTTP status code of code and body as the error body.

You should be able to make another test using Response.error similar to how you did with Response.success

Related