Mockito验证对模拟对象的最后一次调用 [英] Mockito verify the last call on a mocked object

查看:127
本文介绍了Mockito验证对模拟对象的最后一次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些逻辑需要测试,例如:

I have a bit of logic that needs to be tested such as:

{
    ...
    A.add("1");
    ...
    A.add("what ever");
    ...
    A.add("2");
    A.delete("5");
    ...
}

我已经在测试中模拟了A,并且可以测试对参数("2")调用一次add方法,例如:

I have already mocked A in my test and I can test the add method is called once on argument ("2") such as:

Mockito.verify(mockedA).add("2");

我的问题是我该如何测试是否可以验证对方法add的最后一次调用是add("2")而不是其他参数.

My question is how can I test if I can verify the last call on method add is add("2") instead of other arguments.

由于上面的测试无法捕获是否有人无意中在最后添加了另一个调用,例如add("3").请注意,此后我们不再关心A上的其他方法调用.我们也不在乎调用方法的时间,调用方法的顺序. 关键是我们是否可以验证特定嘲笑对象的特定方法的最后一个真实参数.

Since the test above can't catch if somebody by accident adds another call such as add("3") in the last. Please notice that we don't care about other method invocations on A again afterwards. We also don't care about the times of the method called, the sequence of the methods called. The key point here is if we can verify the last true argument on a certain method of a certain mockedObject.

如果您问为什么需要这样的功能,我会说在现实世界中,我们可能需要处理一些设置某些东西的逻辑,而最后一个设置是获胜的,为了避免某人无意间设置了一些其他意外的东西,我想使用我们的UT来捕捉这一点.并且为了不使测试变得过于复杂和整洁,所以我只希望验证对象的特定方法的最后一次调用,而不要验证诸如order/noMoreInteractions/AtMostTimes之类的东西.

If you ask why do you need such functionality, I'd say in real world we might need to handle some logic that set something and the last set wins, and in order to avoid someone by accident set some other thing unexpected and I'd like to use our UT to catch this. And in order not to make the test too complex and neat, so I only expect to verify the last call on a certain method of a object instead verify something like order/noMoreInteractions/AtMostTimes and so on.

推荐答案

在ArgumentCaptor的启发下,感谢@ staszko032,而不是getAllValues并验证序列,我们可以使用captor的getValue,因为captor的getValue始终获取最后一个真实参数.我们可以这样做:

Thanks @staszko032, inspired by the ArgumentCaptor, instead of getAllValues and verify the sequence, we can use getValue of captor since captor's getValue always get the last true argument. We can do it like this:

    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    Mockito.verify(mockedA, Mockito.atLeastOnce()).add(captor.capture());
    Assert.assertEquals("2", captor.getValue());

这篇关于Mockito验证对模拟对象的最后一次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆