我喜欢做以下操作:
.when(
myMock.doSomething(
Matchers.eq( "1" )
)
)
.thenReturn( "1" )
.othwerwise()
.thenThrow( new IllegalArgumentException() );
当然不存在otherwise()
方法,而只是为了向您展示我想完成的工作。
(轻微的免责声明,我从来没有亲自这样做过,只需在Javadoc中阅读它)...如果您在模拟接口上的所有方法都可以使用相同的默认值行为,您可以在模拟上以以下方式设置默认答案。
Foo myMock = Mockito.mock(Foo.class,new ThrowsExceptionClass(IllegalArgumentException.class));
Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");
Javadoc链接:Mockito#模拟和ThrowSexceptionClass
另外,如固执的教程中所讨论的那样,固执事项的顺序和最后的匹配胜利,因此您也可以做:
Foo myMock = Mockito.mock(Foo.class);
Mockito.when(myMock.doSomething(Matchers.any(String.class))).thenThrow(IllegalArgumentException.class);
Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");
您可以创建自己的答案实现,这将注意称为参数:
myMock.doSomething(Mockito.any(String.class)).thenAnswer( myAnswer );
实施上述答案可以做这样的事情:
public String answer(InvocationOnMock invocation) {
if ("1".equals(invocation.getArguments()[0])) {
return "1";
}
else {
throw new IllegalArgumentException();
}
}
只需使用相反的条件即可考虑您的示例本身。当您需要otherwise
时,您可能需要使用not(eq())
:
.when( myMock.doSomething(Matchers.eq( "1" )))
.thenReturn( "1" )
.when( myMock.doSomething(not(Matchers.eq( "1" ))))
.thenThrow( new IllegalArgumentException() );
@charlie接受的答案所描述的方式不起作用(再)。当您尝试覆盖某些参数的一般投掷例外行为时,第一个规则是触发的,并且您有例外(就像您问的那样)。
Mockito.when(myMock.doSomething(any()))
.thenThrow(IllegalArgumentException.class);
Mockito.when(myMock.doSomething(eq("1"))).thenReturn("1"); //An exception is thrown here
// because of the call to .doSomething() on the mock object
要避免使用Mockito.doReturn()
方法:
Mockito.when(myMock.doSomething(any()))
.thenThrow(IllegalArgumentException.class);
Mockito.doReturn("1").when(myMock).doSomething(eq("1"));
最初的问题是doReturn()
根据其Javadoc存在的原因之一:
Here are those rare occasions when doReturn() comes handy:
<...some lines are skipped...>
Overriding a previous exception-stubbing:
hen(mock.foo()).thenThrow(new RuntimeException());
//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
when(mock.foo()).thenReturn("bar");
//You have to use doReturn() for stubbing:
doReturn("bar").when(mock).foo();
使用Java 8 lambda您可以做:
myMock.doSomething(Mockito.any(String.class)).thenAnswer(invocation -> {
Object arg = invocation.getArguments()[0];
if ("1".equals(arg)) {
return "1";
}
throw new IllegalArgumentException("Expected 1 but got " + arg);
});
另外您可以使用验证,如下:
when(myMock.doSomething("1")).thenReturn( "1" );
assertEquals(myMock.doSomething("1"),"1");
verify(myMock).doSomething("1")