如果JUnit测试返回预期的异常,它会成功吗?
你能告诉我如何通过一个简化的例子来实现这样的测试吗?
非常感谢。
发布于 2014-01-16 09:28:39
你为什么不能在考试中抓住你的异常呢?有不同的方法可以做到这一点。就像注释@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);
}
}使用这种方法有几个好处。
发布于 2014-01-16 05:41:50
在JUnit4中,实现这一目标的正确方法是使用一个带有@Rule注释的ExpectedException公共字段,如下所示:
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),但是通常认为前者更优越,原因如下:它允许您在测试中指定应该抛出异常的确切点。如果使用后者,如果测试中的任何一行都抛出(预期类型的)异常,测试就会成功,这通常不是您想要的。
发布于 2014-01-16 05:35:56
测试用例:
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);
}
}https://stackoverflow.com/questions/21139754
复制相似问题