Java:使用 Junit 3 进行异常测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13252572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Exception testing with Junit 3
提问by Mobidoy
I would like to write a test for IndexOutOfBoundsException
. Keep in mind that we are supposed to use JUnit 3.
我想为IndexOutOfBoundsException
. 请记住,我们应该使用 JUnit 3。
My code:
我的代码:
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;
}
}
After some research, I found that you can do this with JUnit 4 using @Test(expected = IndexOutOfBoundsException.class)
but no where did I find how to do this in JUnit 3.
经过一些研究,我发现您可以使用 JUnit 4 执行此操作,@Test(expected = IndexOutOfBoundsException.class)
但我在 JUnit 3 中找不到如何执行此操作的方法。
How can I test this using JUnit 3?
如何使用 JUnit 3 对此进行测试?
回答by Aaron Digulla
Testing exceptions in JUnit 3 uses this pattern:
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
}
The fail()
makes sure you get an error if the code doesn't throw an exception.
fail()
如果代码没有抛出异常,这将确保你得到一个错误。
I use this pattern in JUnit 4 as well since I usually want to make sure the correct values are visible in the exception message and @Test
can't do that.
我也在 JUnit 4 中使用这种模式,因为我通常想确保正确的值在异常消息中可见,但我@Test
不能这样做。
回答by Jon Skeet
Basically, you need to call your method and fail if it doesn'tthrow the right exception - or if it throws anything else:
基本上,你需要调用你的方法,如果它没有抛出正确的异常,或者它抛出其他任何东西,就会失败:
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.
}
回答by Janoz
A simple solution is to add a try catch to the unittest and let the test fail when the exception isn't thrown
一个简单的解决方案是在单元测试中添加一个try catch,并在没有抛出异常时让测试失败
public void testAjouterFail() {
try {
ajouter(-1,null);
JUnit.fail();
catch (IndexOutOfBoundException()) {
//success
}
}
回答by COMCY2002
One thing you can do is use a boolean to run the test to completion and then you can use assert to validate the exception was thrown:
您可以做的一件事是使用布尔值来运行测试直至完成,然后您可以使用 assert 来验证抛出的异常:
boolean passed = false;
try
{
//the line that throws exception
//i.e. illegal argument exception
//if user tries to set the property to null:
myObject.setProperty(null);
}
catch (IllegalArgumentException iaex)
{
passed = true;
}
assertTrue("The blah blah blah exception was not thrown as expected"
, passed);
By using this test, your test will never fail to execute and you can validate that a specific exception type is thrown.
通过使用此测试,您的测试将永远不会执行失败,并且您可以验证是否抛出了特定的异常类型。
回答by karmakaze
Extending @Aaron's solution with some (static import) syntactic sugar allows writing:
使用一些(静态导入)语法糖扩展@Aaron 的解决方案允许编写:
expected(MyException.class,
new Testable() {
public void test() {
... do thing that's supposed to throw MyException ...
}
});
Testable
is like a Runnable which uses test() signature throwing Throwable.
Testable
就像一个 Runnable,它使用 test() 签名抛出 Throwable。
public class TestHelper {
public static void expected(Class<? extends Throwable> expectedClass, Testable testable) {
try {
testable.test();
fail("Expected "+ expectedClass.getCanonicalName() +" not thrown.");
} catch (Throwable actual) {
assertEquals("Expected "+ expectedClass.getCanonicalName() +" to be thrown.", expectedClass, actual.getClass());
}
}
interface Testable {
public void test() throws Throwable;
}
}
You could add checking of the exception message as required.
您可以根据需要添加对异常消息的检查。
回答by Raedwald
In your test method, call ajouter()
inside a try
..catch
block, giving a value of indice
that should cause the exception to be thrown, with
在您的测试方法中,ajouter()
在try
..catch
块内调用,给出一个值indice
应该会导致抛出异常,用
- a
catch
clause that catchesIndexOutOfBoundsException
: in that case return from your test method and thus indicate a pass. - a second
catch
clause that catchesThrowable
: in that case declare a failure (callfail()
), because the wrong kind of exception was thrown - after the
try
..catch
declare a failure (callfail()
), because no exception was thrown.
- 一个
catch
捕获IndexOutOfBoundsException
: 在这种情况下从您的测试方法返回的子句,从而表明通过。 catch
捕获的第二个子句Throwable
:在这种情况下声明失败(调用fail()
),因为抛出了错误类型的异常- 在
try
..catch
声明失败(调用fail()
)之后,因为没有抛出异常。