JUnit / TestNg:如何为同一个异常简化/组合多个{try fail()catch}?

时间:2011-08-12 02:55:40

标签: java unit-testing junit testng

示例(<Expected Exception>&amp; assert 1的{​​{1}}相同):

assert 2

4 个答案:

答案 0 :(得分:2)

如果你喜欢冒险,你也可以试试assertThrows:

https://github.com/dsaff/junit.contrib

随意询问您是否有任何问题。

答案 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);
}