我想为IndexOutOfBoundsException
编写一个测试。请记住,我们应该使用JUnit 3。
我的代码:
public boolean ajouter(int indice, T element) {
if (indice < 0 || indice > (maListe.size() - 1)) {
throw new IndexOutOfBoundsException();
} else if (element != null && !maListe.contains(element)) {
maListe.set(indice, element);
return true;
}
}
经过一些研究,我发现您可以使用JUnit 4使用@Test(expected = IndexOutOfBoundsException.class)
来完成这个任务,但是在JUnit 3中没有找到如何做到这一点的方法。
如何使用JUnit 3进行测试?
发布于 2012-11-06 06:01:35
在JUnit 3中测试异常使用以下模式:
try {
... code that should throw an exception ...
fail( "Missing exception" );
} catch( IndexOutOfBoundsException e ) {
assertEquals( "Expected message", e.getMessage() ); // Optionally make sure you get the correct message, too
}
如果代码没有抛出异常,fail()
将确保得到错误。
我在JUnit 4中也使用这种模式,因为我通常希望确保异常消息中显示正确的值,而@Test
不能这样做。
发布于 2012-11-06 06:00:55
基本上,如果方法没有抛出正确的异常,或者如果它抛出其他任何东西,则需要调用您的方法并失败:
try {
subject.ajouter(10, "foo");
fail("Expected exception");
} catch (IndexOutOfBoundException expect) {
// We should get here. You may assert things about the exception, if you want.
}
发布于 2012-11-06 06:01:26
一个简单的解决方案是在unittest中添加一个try catch,并在未抛出异常时让测试失败
public void testAjouterFail() {
try {
ajouter(-1,null);
JUnit.fail();
catch (IndexOutOfBoundException()) {
//success
}
}
https://stackoverflow.com/questions/13252572
复制相似问题