JUnit:如果捕获到异常,则成功进行测试

时间:2014-01-15 14:16:26

标签: exception junit

如果JUnit测试返回预期的异常,是否有可能成功?

您能告诉我如何通过简化示例实现此类测试吗?

非常感谢。

3 个答案:

答案 0 :(得分:6)

为什么你不能在测试中发现你的异常?有不同的方法可以做到这一点。就像注释@Test(expected = DataAccessException.class)一样,需要根据具体情况使用。但我的建议是以下方式。

public class TestCase{
    @Test
    public void method1_test_expectException () {
     try{
     // invoke the method under test...
     Assert.fail("Should have thrown an exception"); 
     // This above line would only be reached if it doesnt throw an exception thus failing your test. 
                }
     catch(<your expected exception> e){
       Assert.assertEquals(e.getcode(), somce error code);
     }
 }

使用这种方法有几个好处。

  • 如果您有自定义异常,并且有错误代码,则可以 断言错误代码。从而收紧你的测试用例。
  • 相同类型的任何其他意外异常但具有不同的错误 代码将无法通过测试。 (当你连续不断时,这会有所帮助 开发和团队不断重构更新的代码 要求。测试就抓住了它。)

答案 1 :(得分:3)

在JUnit4中实现这一目标的正确方法是使用ExpectedException公共字段,注明@Rule,如下所示:

import org.junit.rules.ExpectedException;
import org.junit.Rule;
import org.junit.Test;


public class MyTestClass {
  @Rule 
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public void aTestThatSucceedsOnlyIfRuntimeExceptionIsThrown() {
      thrown.expect(RuntimeException.class);  
      // invoke code to be tested...
  }
}

请注意,您还使用@Test(expected=RuntimeException.class)但前者通常被认为是优越的,原因如下:它允许您指定测试中应该抛出异常的确切点。如果使用后者,如果中的任何行抛出异常(预期类型),通常不是您想要的,那么测试将成功。

答案 2 :(得分:0)

测试用例:

public class SimpleDateFormatExampleTest {

    @SuppressWarnings("deprecation")
    @Test(expected=ParseException.class)
    public void testConvertStringToDate() throws ParseException {
        SimpleDateFormatExample simpleDateFormatExample = new SimpleDateFormatExample();

    Assert.assertNotNull(simpleDateFormatExample.convertStringToDate("08-16-2011"));

以下内容将在没有(expected=ParseException.class)

的情况下通过
Assert.assertNotNull(simpleDateFormatExample.convertStringToDate("08/16/2011"));

    }

测试类

public class SimpleDateFormatExample {


    public Date convertStringToDate(String dateStr) throws ParseException{
        return new SimpleDateFormat("mm/DD/yyyy").parse(dateStr);
    }
}
相关问题