模拟验证与ArgumentCaptor的交互 [英] mockito verify interactions with ArgumentCaptor

查看:84
本文介绍了模拟验证与ArgumentCaptor的交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要检查与某个方法调用中的参数属于某种类型的模拟的交互次数,可以做到

To check the number of interactions with a mock where the parameter in the method call is of a certain type, one can do

mock.someMethod(new FirstClass());
mock.someMethod(new OtherClass());
verify(mock, times(1)).someMethod(isA(FirstClass.class));

这将归功于对isA的调用,因为someMethod被调用了两次,但仅使用参数FirstClass调用了一次

This will pass thanks to the call to isA since someMethod was called twice but only once with argument FirstClass

但是,即使使用特定参数FirstClass

However, this pattern seems to not be possible when using an ArgumentCaptor, even if the Captor was created for the particular argument FirstClass

这不起作用

mock.someMethod(new FirstClass());
mock.someMethod(new OtherClass());
ArgumentCaptor<FirstClass> captor = ArgumentCaptor.forClass(FirstClass.class);
verify(mock, times(1)).someMethod(captor.capture());

它说该模拟被多次调用.

it says the mock was called more than once.

在捕获参数以进行进一步检查时,有什么方法可以完成此验证?

Is there any way to accomplish this verification while capturing the argument for further checking?

推荐答案

我建议使用Mockito的Hamcrest集成为其编写一个良好的干净匹配器.这样,您就可以将验证与对传递的参数的详细检查结合起来:

I recommend using Mockito's Hamcrest integration to write a good, clean matcher for it. That allows you to combine the verification with detailed checking of the passed argument:

verify(mock, times(1)).someMethod(argThat(personNamed("Bob")));

Matcher<Person> personNamed(final String name) {
    return new TypeSafeMatcher<Person>() {
        public boolean matchesSafely(Person item) {
            return name.equals(item.getName());
        }
        public void describeTo(Description description) {
            description.appendText("a Person named " + name);
        }
    };
}

匹配器通常会导致更具可读性的测试和更有用的测试失败消息.它们也往往非常可重用,并且您会发现自己建立了一个用于测试项目的量身定制的库.最后,您还可以使用JUnit的Assert.assertThat()将它们用于正常的测试断言,因此您将获得双重使用.

Matchers generally lead to more readable tests and more useful test failure messages. They also tend to be very reusable, and you'll find yourself building up a library of them tailored for testing your project. Finally, you can also use them for normal test assertions using JUnit's Assert.assertThat(), so you get double use out of them.

这篇关于模拟验证与ArgumentCaptor的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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