JUnit测试异常

pap*_*uts 82 java junit

我是java的新手.

我正在构造函数上运行一些JUnit测试.构造函数是这样的,如果给它的一个参数给它一个null或一个空字符串,它应该抛出一个异常.

当我在JUnit中使用null或空字符串参数测试此构造函数时,我得到一个红色条,即使我几乎100%确定构造函数方法确实在将这些参数传递给它时引发异常.

如果方法按照预期的方式抛出异常,JUnit中是否应该有绿色条?或者是当你应该得到一个红色条,当异常抛出按照预期的方式工作时?

xyz*_*xyz 127

@Test(expected = Exception.class)  
Run Code Online (Sandbox Code Playgroud)

告诉Junit异常是预期的结果,因此当抛出异常时,测试将被传递(标记为绿色).

对于

@Test
Run Code Online (Sandbox Code Playgroud)

如果抛出异常,Junit会将测试视为失败,前提是它是未经检查的异常.如果检查了异常,它将无法编译,您将需要使用其他方法.此链接可能有所帮助.


rad*_*dai 46

你确定你告诉它期待例外吗?

对于较新的junit(> = 4.7),您可以使用类似的东西(从这里开始)

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

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}
Run Code Online (Sandbox Code Playgroud)

对于较旧的junit,这个:

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
  int i = 1/0;
}
Run Code Online (Sandbox Code Playgroud)


ika*_*ver 6

如果你的构造函数类似于这个:

public Example(String example) {
    if (example == null) {
        throw new NullPointerException();
    }
    //do fun things with valid example here
}
Run Code Online (Sandbox Code Playgroud)

然后,当您运行此JUnit测试时,您将获得一个绿色条:

@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
    Example example = new Example(null);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

使用ExpectedException规则(版本4.7)的一个方法是,您可以测试异常消息,而不仅仅是预期的异常.

使用Matchers,您可以测试您感兴趣的部分消息:

exception.expectMessage(containsString("income: -1000.0"));
Run Code Online (Sandbox Code Playgroud)


Jef*_*ica 5

尽管@Test(expected = MyException.class)ExpectedException规则是非常好的选择,但是在某些情况下,JUnit3样式的异常捕获仍然是最好的方法:

@Test public void yourTest() {
  try {
    systemUnderTest.doStuff();
    fail("MyException expected.");
  } catch (MyException expected) {

    // Though the ExpectedException rule lets you write matchers about
    // exceptions, it is sometimes useful to inspect the object directly.

    assertEquals(1301, expected.getMyErrorCode());
  }

  // In both @Test(expected=...) and ExpectedException code, the
  // exception-throwing line will be the last executed line, because Java will
  // still traverse the call stack until it reaches a try block--which will be
  // inside the JUnit framework in those cases. The only way to prevent this
  // behavior is to use your own try block.

  // This is especially useful to test the state of the system after the
  // exception is caught.

  assertTrue(systemUnderTest.isInErrorState());
}
Run Code Online (Sandbox Code Playgroud)

另一个声称在此提供帮助的库是catch-exception;但是,截至2014年5月,该项目似乎处于维护模式(已被Java 8淘汰),就像Mockito catch-exception只能操作非final方法一样。