2014-01-13 43 views
1

我有一个奇怪的问题,我想测试一个方法,并期望它抛出java.util.NoSuchElementException。这里是我的测试代码:JUnit“预计”似乎没有工作

@Test(expected = NoSuchElementException.class) 
    public void testLineWithoutCommas(){ 
    String lineToTest = "[email protected]"; 
    List<String> linesToTest = new ArrayList<String>(); 
    linesToTest.add(lineToTest); 

    applicationChecker = new ApplicationChecker(); 
    applicationChecker.getLinesFromFile(linesToTest); 
    applicationChecker.getDetailsFromLine(applicationChecker.getLines().get(0)); 
} 

堆栈跟踪看起来预期:

java.util.NoSuchElementException 
at java.util.StringTokenizer.nextToken(Unknown Source) 
at java.util.StringTokenizer.nextElement(Unknown Source) 
at com.scottlogic.cat.util.ApplicationChecker.getDetailsFromLine(ApplicationChecker.java:34) 
at com.scottlogic.cat.utils.ApplicationCheckerTest.testLineWithoutCommas(ApplicationCheckerTest.java:42) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
and more boring stuff... 

最后的JUnit:

java.lang.AssertionError: Expected exception: java.util.NoSuchElementException 
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32) 
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) 
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) 
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) 
and blah blah blah... 

任何想法有什么不对?谢谢你的帮助。

+0

过得好*双向*堆栈跟踪?我期望看到其中一个,但不是两个。 –

+0

究竟是吧?我不知道它有什么问题... – Lucas

+0

卢卡斯,他的意思是 - “你是如何得到它们的”。不“并不奇怪”。 –

回答

3

检查您没有捕获并处理代码中某处的NoSuchElementException。第一次堆栈跟踪可能是由于你的代码捕获异常,然后将其记录下来并将其作为其他内容抛出,或者只是将其捕获并且根本不抛出。 'expected'只会捕获从测试本身抛出的异常,它不会处理异常抛出和部分通过代码处理。

0

试试吧

@Rule 
public ExpectedException exc = ExpectedException.none(); 

@Test 
public void testLineWithoutCommas(){ 

exc.expect(NoSuchElementException.class); 
// method have exception 

}