[英]How do I handle unmatched parameters in Mockito?
我喜歡做以下的事情:
.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
或者,正如Stubbing教程中所討論的那樣, 存根的順序很重要並且最后匹配獲勝,所以您也可以這樣做:
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");
你可以創建自己的Answer實現,它會關注被調用的參數:
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();
}
}
只是使用相反的條件,即考慮你的例子本身。 您可能需要使用not(eq())
當你需要otherwise
:
.when( myMock.doSomething(Matchers.eq( "1" )))
.thenReturn( "1" )
.when( myMock.doSomething(not(Matchers.eq( "1" ))))
.thenThrow( new IllegalArgumentException() );
使用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);
});
@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();
或者,您可以使用驗證,如下所示:
when(myMock.doSomething("1")).thenReturn( "1" );
assertEquals(myMock.doSomething("1"),"1");
verify(myMock).doSomething("1")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.