Java如何在Junit-eclipse中使用注释
我试图用下面的代码测试Junit中是否有方法抛出IllegalArgumentException,但它不起作用。Eclipse建议创建一个注释类,这让我有点困惑。我可以不使用注释就离开吗?否则,最好的解决方案是什么Java如何在Junit-eclipse中使用注释,java,exception,testing,junit,annotations,Java,Exception,Testing,Junit,Annotations,我试图用下面的代码测试Junit中是否有方法抛出IllegalArgumentException,但它不起作用。Eclipse建议创建一个注释类,这让我有点困惑。我可以不使用注释就离开吗?否则,最好的解决方案是什么 @Test(expected = IllegalArgumentException.class) public void testRegister(){ myProgram.register(-23); //the argument shoul
@Test(expected = IllegalArgumentException.class)
public void testRegister(){
myProgram.register(-23); //the argument should be positive
}
如果不想使用注释,可以捕获所有异常并在断言中测试该异常是否为实例IllegalArgumentException
Exception e = null;
try {
// statement that should cause exception
} catch(Exception exc) {
e = exc;
}
// Assert that e is not null to make sure an exception was thrown
// Assert that e is of type IllegalARgumentException
但最终,只使用JUnit注释要简单得多。这对我来说似乎是正确的。我通常会尝试捕获与我相关的异常,如果捕获到,就会通过测试。试着这样做:
try {
myProgram.register(-23);
// (optional) fail test here
}
catch (IllegalArgumentException e){
// pass test here
}
catch (Exception e) {
// (optional) fail test here
}
您的测试代码似乎是正确的,可能是
test
ieregister
下的方法根本没有抛出IllegalArgumentException
。在这种情况下,您需要修复register
方法的实现。我通常使用try-catch,捕获我感兴趣的异常,并在该catch块中通过测试。您说的“它不工作”是什么意思?到底是什么问题?您可能正在使用junit3。注释仅在junit4中可用。如果您使用的是junit4,您可以(也可能应该)将测试方法重命名为更有意义的方法。@tobypls您能详细介绍一下如何使用try-and-catch吗?谢谢!我们是否需要在catch块中添加任何代码,比如断言什么,或者我们可以将其留空?很抱歉,我不清楚这一点。我懒得检查JUnit的语法。无论何时返回
或assertTrue(true)
,测试都将通过。请参阅,以了解有关该问题的更多信息。要失败,请调用fail()
。