哪个更好,ExpectedException或@Test(期望=

Pri*_*shi 13 java junit exception

我有代码,我在jUnit中检查异常.我想知道以下哪个是一个很好的jUnit练习?

第一

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

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

第二

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

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

Mat*_*ell 17

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

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

但是,@ 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

使用旧式(Junit 3)throw/catch的一个原因是,如果您有特定要求.这些并不多,但可能会发生:

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