ArgumentCaptor 出现问题并连续调用相同方法(错误或功能?)
我遇到 ArgumentCaptor 无法记录的问题 多次调用同一方法时的参数。 基本上这似乎不起作用:
List<Dummy> mList = mock(List.class);
Dummy dummy = new Dummy();
when(mList.get(anyInt())).thenReturn(dummy);
Dummy d = mList.get(12);
d.setName("John");
mList.add(d);
Dummy g = mList.get(10);
g.setName("Ben");
mList.add(g);
...
verify(mymock, times(3)).doStuff(captor.capture));
assertEquals("John", captor.getAllValues().get(0).getName());
assertEquals("Ben", captor.getAllValues().get(1).getName());
assertEquals("Don", captor.getAllValues().get(2).getName());
getName() 的值始终设置为“Don”。 我也尝试过使用 InOrder,结果相同。
功能(和我愚蠢的)还是错误?
为了更好地解释这个问题,我创建了一个用例: http://pastebin.com/RE1UzJ4F
干杯
I'm having a problem with ArgumentCaptor not being able to record the
arguments when calling the same method a number of times.
Basically this does not seem to work:
List<Dummy> mList = mock(List.class);
Dummy dummy = new Dummy();
when(mList.get(anyInt())).thenReturn(dummy);
Dummy d = mList.get(12);
d.setName("John");
mList.add(d);
Dummy g = mList.get(10);
g.setName("Ben");
mList.add(g);
...
verify(mymock, times(3)).doStuff(captor.capture));
assertEquals("John", captor.getAllValues().get(0).getName());
assertEquals("Ben", captor.getAllValues().get(1).getName());
assertEquals("Don", captor.getAllValues().get(2).getName());
The value of getName() is always set to "Don".
I have also tried using InOrder, with the same outcome.
Feature (and me stupiud) or bug?
To better explain the issue I have created a use case:
http://pastebin.com/RE1UzJ4F
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ArgumentCaptor 的 java 文档建议您正在尝试什么,所以我认为这是一个错误。但是,这是您的代码中的错误。
问题是您每次调用 setName(..) 时都会更改同一个虚拟对象的名称。我建议您将 Dummy 设置为不可变,并尽可能避免设置器。这将避免这些类型的错误。
如果你不能让你的虚拟对象不可变来强制解决这个问题,你至少应该从每次获取中传递一个不同的实例。这样做
可以解决问题。
The java doc for ArgumentCaptor suggests what you are trying, so I'd say this is a bug. However, it is a bug in your code.
The problem is that you're changing the name of the same dummy each time you're invoking setName(..). I'd suggest that you make Dummy immutable and avoid setters wherever you can. That will avoid these types of bugs.
If you cannot make your Dummy immutable to force the issue you should at least pass a different instance from each get. Doing
Would fix the problem.
艾维恩是正确的;然而,在某些情况下(例如嵌入式系统),内存不足,您不想使用或不能使用不变性。
我发现的一种解决方法是为每次调用使用不同的模拟,然后验证每个模拟都有一个调用的模拟列表。
它不是那么漂亮,但是您不必以这种方式使您的类不可变。
iwein is correct; however, there are some situations (such as embedded systems) in which memory is scarce and you do not want to use or cannot use immutability.
A workaround I have found is to use a different mock for each invocation, then verify a list of mocks that each have one invocation.
It is not as pretty, but you do not have to make your classes immutable this way.
我遇到了这个问题,最终使用了 atLeastOnce,如下所示:
I had this problem and ended up using
atLeastOnce
, like so: