如何进行第 3 次测试以检查异常消息中是否存在 cause1?我还列出了前两个测试中有缺点的地方。首先是不检查消息,其次需要大量样板代码。
public class CheckExceptionsWithMockitoTest {
@Test(expected = RuntimeException.class)
public void testExpectedException1() {
A a = new A();
a.doSomethingThatThrows();
}
@Test
public void testExpectedException2() {
A a = new A();
try {
a.doSomethingThatThrows();
fail("no exception thrown");
} catch (RuntimeException e) {
assertThat(e.getMessage(), org.hamcrest.Matchers.containsString("cause1"));
}
}
@Test
public void testExpectedException3() {
A a = new A();
A spyA = org.mockito.Mockito.spy(a);
// valid but doesnt work
// doThrow(new IllegalArgumentException()).when(spyA).doSomethingThatThrows();
// invalid but in the spirit of what i want
//chekThrow(RuntimeException.class,containsString("cause1")).when(spyA).doSomethingThatThrows();
}
}
我在 Mockito 中找不到有用的东西,但有些东西看起来可能(在语法级别)和功能。
使用 catchexception 我创建了这样的测试
import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
public class CheckExceptionsWithMockitoTest{
//...
@Test
public void testExpectedException3() {
A a = new A();
verifyException(a,IllegalArgumentException.class)
.doSomethingThatThrows();
//if more details to be analized are needed
assertThat(
(IllegalStateException) caughtException(),
allOf(
is(IllegalStateException.class),
hasMessageThat(
containsString("is not allowed to add counterparties")),
hasNoCause()));
//more asserts could come
assertNotNull(a);
}
}
最佳答案
使用catch-exception库,或者我猜您正在寻找的解决方案是您的第二个实现。
@expected 没有提供任何方法来断言抛出的异常,除了它的类,所以你不能避免 try/catching(没有那么多样板代码!)
Mockito 不提供类似verifyThrows 方法的东西。
因此您可以用 try/catching 换取额外的库:使用 catch-exception ,您将能够在一行中捕获异常,并为进一步的断言做好准备。
示例源代码
A a = new A();
when(a).doSomethingThatThrows();
then(caughtException())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("is not allowed to add counterparties")
.hasNoCause();
依赖
'com.googlecode.catch-exception:catch-exception:1.2.0'
关于java - mockito 使用 spy 进行更好的预期异常测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772939/