我在谷歌上搜索了一下,但没有找到任何相关信息。我得到了这样的东西:
Object obj = getObject();
Mockeable mock= Mockito.mock(Mockeable.class);
Mockito.when(mock.mymethod(obj )).thenReturn(null);
Testeable testableObj = new Testeable();
testableObj.setMockeable(mock);
command.runtestmethod();
现在,我想验证在runtestmethod()内部调用的mymethod(Object o)是否与对象o一起调用,而不是任何其他方法。但我总能通过测试,不管我用什么来验证,比如:
Mockito.verify(mock.mymethod(Mockito.eq(obj)));
or
Mockito.verify(mock.mymethod(Mockito.eq(null)));
or
Mockito.verify(mock.mymethod(Mockito.eq("something_else")));
我总是通过考试。我如何完成验证(如果可能的话)?
谢谢你!
上面的许多答案让我感到困惑,但我怀疑这可能是由于Mockito的旧版本。这个答案是通过使用完成的
爪哇 11
莫皮托 3.1.0
春季引导 2.2.7.发布
JUnit5
使用ArgumentCaptor我是这样做的:
@Mock
MyClientService myClientService;
@InjectMocks
MyService myService;
@Test
void myTest() {
ArgumentCaptor<String> captorParam1 = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> captorParam2 = ArgumentCaptor.forClass(String.class);
Mockito.when(myClientService.doSomething(captorParam1.capture(), captorParam2.capture(), ArgumentMatchers.anyString()))
.thenReturn(expectedResponse);
assertDoesNotThrow(() -> myService.process(data));
assertEquals("param1", captorParam1.getValue());
assertEquals("param2", captorParam2.getValue());
verify(myClientService, times(1))
.doSomething(anyString(), anyString(), anyString());
}
我用过Mockito。以这种方式验证
@UnitTest
public class JUnitServiceTest
{
@Mock
private MyCustomService myCustomService;
@Test
public void testVerifyMethod()
{
Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); // no other method called except this
}
}
你正在尝试使用对象的.equals方法来做逻辑相等吗?你可以利用Mockito中包含的argThat匹配器来做到这一点
import static org.mockito.Matchers.argThat
接下来,你可以实现自己的参数匹配器,它将遵循每个对象的.equals方法
private class ObjectEqualityArgumentMatcher<T> extends ArgumentMatcher<T> {
T thisObject;
public ObjectEqualityArgumentMatcher(T thisObject) {
this.thisObject = thisObject;
}
@Override
public boolean matches(Object argument) {
return thisObject.equals(argument);
}
}
现在使用您的代码,您可以将其更新为…
Object obj = getObject();
Mockeable mock= Mockito.mock(Mockeable.class);
Mockito.when(mock.mymethod(obj)).thenReturn(null);
Testeable obj = new Testeable();
obj.setMockeable(mock);
command.runtestmethod();
verify(mock).mymethod(argThat(new ObjectEqualityArgumentMatcher<Object>(obj)));
如果你只是想要EXACT相等(内存中相同的对象),就这样做
verify(mock).mymethod(obj);
这将验证它被调用过一次。