如何在Mockito中处理不匹配的参数?

时间:2012-10-25 03:44:43

标签: java junit mockito

我喜欢做以下事情:

.when( 
    myMock.doSomething(
        Matchers.eq( "1" )
    ) 
)
.thenReturn( "1" )
.othwerwise()
.thenThrow( new IllegalArgumentException() );

当然otherwise()方法不存在,只是为了向您展示我想要完成的任务。

6 个答案:

答案 0 :(得分:20)

(轻微的免责声明,我从来没有亲自完成这个,只是在javadoc中读到它)...如果你的模拟界面上的所有方法都可以使用相同的默认行为,你可以{{3}以这样的方式:

Foo myMock = Mockito.mock(Foo.class,new ThrowsExceptionClass(IllegalArgumentException.class));
Mockito.when(myMock.doSomething(Matchers.eq("1"))).thenReturn("1");

JavaDoc链接:set the default answer on your mockMockito#mock

或者,正如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");

答案 1 :(得分:7)

你可以创建自己的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();
    }
} 

答案 2 :(得分:5)

只是使用相反的条件,即考虑你的例子本身。您可能需要在需要not(eq())时使用otherwise

 .when( myMock.doSomething(Matchers.eq( "1" )))
     .thenReturn( "1" )
 .when( myMock.doSomething(not(Matchers.eq( "1" ))))
     .thenThrow( new IllegalArgumentException() );

答案 3 :(得分:1)

使用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);
});

答案 4 :(得分:1)

@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();

答案 5 :(得分:-1)

或者您可以使用验证,如下所示:

when(myMock.doSomething("1")).thenReturn( "1" );
assertEquals(myMock.doSomething("1"),"1");
verify(myMock).doSomething("1")