mockito - 使用值列表中的值之一在匹配器中进行比较

问题描述 投票:0回答:4

我的方法接口是

Boolean isAuthenticated(String User)

我想从值列表中进行比较,如果有任何用户从列表中传递到函数中,那么它应该返回 true。

when(authService.isAuthenticated(or(eq("amol84"),eq("arpan"),eq("juhi")))).thenReturn(true);

我正在使用附加参数匹配器“或”,但上面的代码不起作用。我该如何解决这个问题?

junit mockito matcher
4个回答
10
投票

or
没有三参数重载。 (见文档。)如果您的代码编译通过,您可能导入了与
or
不同的
org.mockito.AdditionalMatchers.or
方法。

or(or(eq("amol84"),eq("arpan")),eq("juhi"))
应该工作。

您也可以尝试

oneOf
Hamcrest匹配器(以前是
isOneOf
),通过
argThat
Mockito匹配器
访问:

when(authService.isAuthenticated(
         argThat(is(oneOf("amol84", "arpan", "juhi")))))
    .thenReturn(true);

3
投票

您可以定义单独的答案:

when(authService.isAuthenticated(eq("amol84"))).thenReturn(true);
when(authService.isAuthenticated(eq("arpan"))).thenReturn(true);
when(authService.isAuthenticated(eq("juhi"))).thenReturn(true);

1
投票

如果您对引入库不感兴趣,您可以迭代所有要添加到模拟中的值:

// some collection of values
List<String> values = Arrays.asList("a", "b", "c");

// iterate the values
for (String value : values) {
  // mock each value individually
  when(authService.isAuthenticated(eq(value))).thenReturn(true)
}

-1
投票

对我来说这行得通:

public class MockitoTest {

    Mocked mocked = Mockito.mock(Mocked.class);

    @Test
    public void test() {
        Mockito.when(mocked.doit(AdditionalMatchers.or(eq("1"), eq("2")))).thenReturn(true);

        Assert.assertTrue(mocked.doit("1"));
        Assert.assertTrue(mocked.doit("2"));
        Assert.assertFalse(mocked.doit("3"));
    }
}

interface Mocked {
    boolean doit(String a);
}

检查您是否正确设置了 mockito,或者您是否使用了与我相同的 Matchers。

© www.soinside.com 2019 - 2024. All rights reserved.