Java Mockito抛出异常

Java Mockito抛出异常,java,junit,mockito,Java,Junit,Mockito,我试过这样做。我得到了以下例外 public interface ABC { public boolean removeUser(String userId) throws OTPServiceException, RemoteException; } ABC abc= mock(ABC.class); doNothing().when(abc).removeUser(anyString()); org.mockito.exceptions.base.MockitoExcep

我试过这样做。我得到了以下例外

public interface ABC {
        public boolean removeUser(String userId) throws OTPServiceException, RemoteException;
}

ABC abc= mock(ABC.class);
doNothing().when(abc).removeUser(anyString());
org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called

对于非
void
方法,您不能
doNothing
,因为您需要返回某些内容或抛出异常

public interface ABC {
        public boolean removeUser(String userId) throws OTPServiceException, RemoteException;
}

ABC abc= mock(ABC.class);
doNothing().when(abc).removeUser(anyString());
org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called

方法返回布尔值,因此应该模拟布尔响应

你应该有这样的东西:

when(abc.removeUser(anyString())).thenReturn(true);

when(abc.removeUser(anyString())).thenThrow(RuntimeException.class);

您可以查看更详细、更简单的解释。

您担心什么?您能解释一下您的问题吗?他问您的问题是什么。这条消息非常清楚,“只有void方法才能执行任何操作()!”所以你可以用谷歌搜索这条消息并解决你的问题?!编辑响应以使其正确。我在调用removeUser时返回(anyString()),应该在when(…)方法的结果上调用它。