Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何模拟无效呼叫?_Java_Android_Unit Testing_Mockito_Retrofit - Fatal编程技术网

Java 如何模拟无效呼叫?

Java 如何模拟无效呼叫?,java,android,unit-testing,mockito,retrofit,Java,Android,Unit Testing,Mockito,Retrofit,在我的api(带改装)中,我有很多这样的请求: public Call<Void> postAsyncReserveDevice(@NonNull ReservedWorkerData data, @NonNull String token) { return apiService.postReservedWorker( data, ApiPrefs.TOKEN_PREFIX + token); }

在我的api(带改装)中,我有很多这样的请求:

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

        return apiService.postReservedWorker(
                data,
                ApiPrefs.TOKEN_PREFIX + token);
}
看起来不错,但当我运行测试用例时,我看到错误:

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

如何在我的api中模拟和测试这些方法?

该方法返回
调用
,那么为什么不在模拟方法中返回:
Mockito.any(Call.class)

例如:

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

虽然它在编译时会发出警告,因为它声明了一个原始
调用

我使用Kotlin的解决方案:

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

仅此而已

您是否尝试过使用
any(Void.class)
?没有。我用另一种方式。但这也行!(我的解决方案太愚蠢了:
…然后返回(Calls.response(makeVoid());私有Void makeVoid(){returnnull}
@Test
fun the_test() {
    val call: Call<Void> = Calls.response(makeVoid())
    `when`(apiManager.enablePushNotification(any())).thenReturn(call)
    ...
}
private fun makeVoid(): Void? = null