2014-10-01 96 views
0

我想要测试一个方法在Junit中是否会抛出IllegalArgumentException,但是它不起作用。 Eclipse建议创建一个注释类,这让我感到困惑。我可以不使用注释而离开吗?否则,最好的解决方案是什么?如何在Junit中使用注释 - eclipse

@Test(expected = IllegalArgumentException.class) 
     public void testRegister(){ 
      myProgram.register(-23); //the argument should be positive 
     } 
+0

你的测试代码看起来是正确的,可能是'test'下的''方法'即'register'根本就没有抛出'IllegalArgumentException'。在这种情况下,你需要修改'register'方法的实现。 – 2014-10-01 10:01:52

+0

我通常使用try-catch,捕捉我感兴趣的异常并通过该catch块中的测试。 – tobypls 2014-10-01 11:02:47

+0

你是什么意思“它没有工作”到底是什么问题? – dkatzel 2014-10-01 15:24:50

回答

1

我通常会尝试捕捉我感兴趣的异常,并在通过测试时发现它。试试这样的:

try { 
    myProgram.register(-23); 
    // (optional) fail test here 
} 
catch (IllegalArgumentException e){ 
    // pass test here 
} 
catch (Exception e) { 
    // (optional) fail test here 
} 
+0

谢谢!我们是否需要在catch块中添加任何代码,比如声明某些东西,或者我们可以将其留空? – stillAFanOfTheSimpsons 2014-10-02 02:43:59

+1

对不起,我不清楚这一点。我懒得检查JUnit的语法。任何时候你'返回'或'assertTrue(true)',测试将**通过**。请参阅[本文](http://stackoverflow.com/questions/4036144/junit4-fail-is-here-but-where-is-pass)了解更多信息。要失败**,请调用'fail()'。 – tobypls 2014-10-02 07:32:37

0

如果您不想使用注释,则可以捕获所有异常并在断言中测试该异常是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注解要简单得多。这对我来说似乎是正确的。