'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("",""))
}


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Textnovian