abbath0767
abbath0767

Reputation: 986

How to mock Void Call?

In my api (with Retrofit) i have lot of requests which like this:

public Call<Void> postAsyncReserveDevice(@NonNull ReservedWorkerData data, @NonNull String token) {

        return apiService.postReservedWorker(
                data,
                ApiPrefs.TOKEN_PREFIX + token);
}

where i ignore result of response - he successful or not and this is important.

But I faced a problem in unit test. I need mock the api answer:

@Test
public void test() {
//...
when(apiService.postAsyncReserveDevice(
                eq(data), any(String.class)))
                .thenReturn(Calls.response(Any() as Void))
//...
}

Looks good, but when i run test case i see error:

java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Void

How mock and test such methods in my api?

Upvotes: 1

Views: 1207

Answers (2)

Carlos Daniel
Carlos Daniel

Reputation: 2699

The solution that I use to use using Kotlin:

@Test
fun the_test() {
    val call: Call<Void> = Calls.response(makeVoid())
    `when`(apiManager.enablePushNotification(any())).thenReturn(call)
    ...
}

And the helper function:

private fun makeVoid(): Void? = null

That's all

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

The method returns Call<Void>, so why not return in the mocked method : Mockito.any(Call.class) ?

For example :

Mockito.when(mock.postAsyncReserveDevice()).thenReturn(Mockito.any(Call.class));

While it will produce a warning at compile time as it declares a raw Call.

Upvotes: 1

Related Questions