示例(<Expected Exception>
&amp; assert 1
的{{1}}相同):
assert 2
答案 0 :(得分:2)
答案 1 :(得分:1)
如果将其分解为单独的测试方法太难了,那么过去这对我有用。
创建一个需要expectsException()
。
Callback
interface Callback {
void call() throws Exception;
}
void expectsException(Callback callback) {
try {
callback.call();
fail("ExpectedException was not thrown!");
} catch (Exception e) {
if (!(e instanceof ExpectedException)) {
fail("Expecting ExpectedException, got " + e.getClass());
}
assertEquals("Expected exception message", e.getMessage());
}
}
然后,将代码包装在try {...} catch
:
Callback
块内
@Test
public void testSomething() {
expectsException(new Callback() {
public void call() throws Exception {
// assert 1
}
});
expectsException(new Callback() {
public void call() throws Exception {
// assert 2
}
});
}
但是请注意,根据您在catch
区块中的操作,这可能会或者可能不会比简单try {...} catch
更简洁。
(当Java得到正确的闭包时,这种方法会更有意义。)
答案 2 :(得分:1)
你应该把你的方法分成两个单独的方法,每个方法都抛出:
@Test(expectedExceptions = NullPointerException.class)
public void testCase1() {
// assert 1
}
@Test(expectedExceptions = NullPointerException.class)
public void testCase2() {
// assert 2
}
答案 3 :(得分:0)
catch-exception可能有所帮助:
public void testCase() {
// assert 1
verifyException(obj, MyException.class).do(1);
// assert 2
verifyException(obj, MyException.class).do(2);
}