![](/img/trans.png)
[英]Mockito using argument matchers for when call on method with variable number of arguments
[英]Using Mockito is there a way to throw an exception on method call when there are no valid matchers
我有一個模擬的 class,我想在沒有有效匹配器時拋出異常而不是返回null
。 mockito 這可能嗎? 這個想法是我已經模擬了使用某些參數的方法。 當這些都不匹配時,拋出異常而不是返回null
。
您可以編寫自定義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.