哪个更好,ExpectedException或@Test(expected= [已关闭]

2022-09-03 06:31:14

我有代码检查jUnit中的异常。我想知道以下哪项是好的jUnit实践?

第一

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void checkNullObject() throws CustomException {
    exception.expect(CustomException.class);
    MyClass myClass= null;
    MyCustomClass.get(null);
}

第二

@Test(expected=CustomException.class)
public void checkNullObject() throws CustomException {
    MyClass myClass= null;
    MyCustomClass.get(null);    
}

编辑:请注意,CustomException 是一个未经检查的自定义异常。(虽然它不会对这个问题产生任何影响)。


答案 1

这取决于您要签入异常的内容。如果您所做的只是检查是否引发异常,那么使用可能是最简单的方法:@Test(expected=...)

@Test(expected=CustomException.class)
public void checkNullObject() throws CustomException {
  MyClass myClass= null;
  MyCustomClass.get(null);
}

但是,@Rule ExpectedException具有更多选项,包括从javadoc检查消息:

// These tests all pass.
public static class HasExpectedException {
    @Rule
    public ExpectedException thrown= ExpectedException.none();

    @Test
    public void throwsNothing() {
        // no exception expected, none thrown: passes.
    }

    @Test
    public void throwsNullPointerException() {
        thrown.expect(NullPointerException.class);
        throw new NullPointerException();
    }

    @Test
    public void throwsNullPointerExceptionWithMessage() {
        thrown.expect(NullPointerException.class);
        thrown.expectMessage("happened?");
        thrown.expectMessage(startsWith("What"));
        throw new NullPointerException("What happened?");
    }

    @Test
    public void throwsIllegalArgumentExceptionWithMessageAndCause() {
        NullPointerException expectedCause = new NullPointerException();
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("What");
        thrown.expectCause(is(expectedCause));
        throw new IllegalArgumentException("What happened?", cause);
    }
}

因此,您可以检查消息,异常的原始原因。要检查消息,您可以使用匹配器,以便进行检查和类似检查。startsWith()

使用旧式(Junit 3)投掷/接球的一个原因是如果您有特定的要求。这些并不多,但它可能发生:

@Test
public void testMe() {
    try {
        Integer.parseInt("foobar");
        fail("expected Exception here");
    } catch (Exception e) {
        // OK
    }
}

答案 2

第二个版本绝对是这样做的标准方法。在Junit 4之前,老式的学校方法看起来像这样:

try {
    codeThatShouldThrowException();
    fail("should throw exception");
} catch (ExpectedException expected) {
    //Expected
}

有时,您可能希望还原到这种方式,例如,如果要断言异常中有关消息的某些内容。