0

Mockito 有没有办法验证是否使用封闭集中的参数调用方法。例如,我可以断言一个方法

void addToNotWorthyList(String guitaristName);

被称为与 guitaristName 在集合内(“Jeff Beck”、“Seasick Steve”、“Steve Howe”)?

4

3 回答 3

5
verify(systemUnderTest).addToNotWorthyList(argThat(isOneOf(
    "Jeff Beck", "SeasickSteve", "Steve Howe")));

这使用了 Hamcrest 的isOneOf,至少在 1.3 中可用。如果您已经拥有集合或数组中的项目,请直接跳至isIn​​.

verify(systemUnderTest).addToNotWorthyList(argThat(isIn(setOfNames)));
于 2013-11-06T19:20:44.847 回答
1

您至少可以使用answersargument captors来做到这一点。

public class MyTest {
    class Idols {
        void addToNotWorthyList(String guitaristName) {
            //testing purposes
        }
    }

    private List<String> expectedValues = new ArrayList() {{
        add("Jeff Beck");
        add("Seasick Steve");
        add("Steve Howe");
    }};

    @Mock
    private Idols mock;

    @Before
    public void setup() {
        initMocks(this);
    }

    @Test
    public void checkWithAnswer() {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                String actualGuitarist = (String) invocation.getArguments()[0];
                assertTrue("Found unexpected guitarist [" + actualGuitarist + "]", expectedValues.contains(actualGuitarist));
                return null;
            }
        }).when(mock).addToNotWorthyList(anyString());

        mock.addToNotWorthyList("Jeff Beck");
        mock.addToNotWorthyList("Jeff");

        verify(mock, atLeast(0)).addToNotWorthyList(anyString());
    }

    @Test
    public void checkWithArgumentCaptor() {
        ArgumentCaptor<String> usedGuitarists = ArgumentCaptor.forClass(String.class);

        mock.addToNotWorthyList("Jeff Beck");
        mock.addToNotWorthyList("Jeff");

        verify(mock, atLeast(0)).addToNotWorthyList(usedGuitarists.capture());
        for (String actualGuitarist : usedGuitarists.getAllValues()) {
            assertTrue("Found unexpected guitarist [" + actualGuitarist + "]", expectedValues.contains(actualGuitarist));
        }
    }
}
于 2013-11-06T19:24:25.750 回答
0

FWIW ..这是我想出的

public class SetMatcher<T> extends ArgumentMatcher<T> {

   private final Set<T> set;

   public MockitoSetMatcher(List<T> list) {
      set = new HashSet<T>(list);
   }

   @Override
   public boolean matches(Object argument) {
      return set.contains(argument);
   }

}

然后我使用

Mockito.argThat(new SetMatcher<String>(Arrays.asList(new String[] { "Jeff Beck", "Seasick Steve", "Steve Howe" } )));
于 2013-11-06T19:15:49.903 回答