4

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("",""))
}
YasudaYutaka
  • 43
  • 1
  • 4

1 Answers1

2

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

Textnovian
  • 114
  • 5
  • I tried to use this Response.error, but I don't know what to insert on the second parameter (okhttp3.ResponseBody body), I tried to insert LoginResponse(status = "NOK") but it didn't worked – YasudaYutaka Feb 19 '22 at 00:20
  • 2
    check out https://stackoverflow.com/questions/33153100/how-to-create-a-retrofit-response-object-during-unit-testing-with-retrofit-2 – Textnovian Feb 19 '22 at 00:29