mockito anyList 给定大小

mockito anyList of a given size(mockito anyList 给定大小)
本文介绍了mockito anyList 给定大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 mockito 验证一个方法已被调用.方法:

I'm verifying with mockito that a method has been called. The method:

public void createButtons(final List<Button> buttonsConfiguration) {...}

由于传递哪个列表并不重要,因此我验证该方法的调用如下:

Since It doesn't matter which list is passed I verify that the method is called as follows:

verify(mock).createButtons(Matchers.anyListOf(Button.class));

但是,List 的大小很重要.因此,哪个 List 并不重要,但列表必须有 X 个元素.

But, the size of the List is important. So, it doesn't matter which List but the list has to have X elements.

这可能吗?

推荐答案

一种方法是使用 Captor

One way is to use a Captor

ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(mock).createButtons(captor.capture());
assertEquals(x, captor.getValue().size()); // if expecting single list
assertEquals(x, captor.getValues().size()); // if expecting multiple lists

请参阅 http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#15 获取文档.

您还可以使用自定义参数匹配器.该文档显示了一个完全符合您要求的示例:

You could also use a custom argument matcher. The documentation shows an example that does exactly what you want:

http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentMatcher.html

 class IsListOfTwoElements extends ArgumentMatcher<List> {
     public boolean matches(Object list) {
         return ((List) list).size() == 2;
     }
 }
 
 List mock = mock(List.class);
 when(mock.addAll(argThat(new IsListOfTwoElements()))).thenReturn(true);
 mock.addAll(Arrays.asList("one", "two"));
 verify(mock).addAll(argThat(new IsListOfTwoElements()));

例如,您还可以添加一个构造函数,以便指定所需的列表大小等.

You could, for instance, also add a constructor so you can specify list size desired, etc.

这篇关于mockito anyList 给定大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)