我的方法接口是
Boolean isAuthenticated(String User)
我想从值列表中进行比较,如果有任何用户从列表中传递到函数中,那么它应该返回 true。
when(authService.isAuthenticated(or(eq("amol84"),eq("arpan"),eq("juhi")))).thenReturn(true);
我正在使用附加参数匹配器“或”,但上面的代码不起作用。我该如何解决这个问题?
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);
您可以定义单独的答案:
when(authService.isAuthenticated(eq("amol84"))).thenReturn(true);
when(authService.isAuthenticated(eq("arpan"))).thenReturn(true);
when(authService.isAuthenticated(eq("juhi"))).thenReturn(true);
如果您对引入库不感兴趣,您可以迭代所有要添加到模拟中的值:
// 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)
}
对我来说这行得通:
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。