[英]Using Mockito is there a way to throw an exception on method call when there are no valid matchers
I have a mocked class that I'd like to throw an exception rather than returning null
when there are no valid matchers.我有一个模拟的 class,我想在没有有效匹配器时抛出异常而不是返回null
。 Is this possible with mockito? mockito 这可能吗? The idea is that I've mocked the method to work with certain parameters.这个想法是我已经模拟了使用某些参数的方法。 When none of those match, rather than returning null
, throw an exception.当这些都不匹配时,抛出异常而不是返回null
。
You can write custom org.mockito.stubbing.Answer<T>
and use one with thenAnswer
:您可以编写自定义org.mockito.stubbing.Answer<T>
并将其与thenAnswer
一起使用:
private final static String EXCEPTION_MSG = "no valid matchers";
private final static String A = "A", B = "B";
private final static Map<String, String> argsReturnVal = new HashMap<>();
static {
argsReturnVal.put(A, B);
}
private static final Answer<String> throwAnswer = a ->
argsReturnVal.computeIfAbsent(
a.getArgument(0),
mf -> { throw new IllegalArgumentException(EXCEPTION_MSG); }
);
@Mock
private Checker<String> checker;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
Mockito.when(checker.check(Mockito.anyString())).thenAnswer(throwAnswer);
}
@Test
public void testThrow() {
Assert.assertEquals(B, checker.check(A));
try {
checker.check("X-X-X");
} catch (IllegalArgumentException ex) {
Assert.assertEquals(EXCEPTION_MSG, ex.getMessage());
}
}
private interface Checker<T> {
String check(T in);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.