Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a Retrofit Response

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("",""))
}
like image 528
YasudaYutaka Avatar asked Sep 17 '25 02:09

YasudaYutaka


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

like image 158
Textnovian Avatar answered Sep 19 '25 17:09

Textnovian