简体   繁体   English

JUnit“预期”似乎不起作用

[英]JUnit “expected” doesn't seem to work

I have a wierd problem, I am trying to test a method and expecting it to throw java.util.NoSuchElementException. 我有一个奇怪的问题,我试图测试一个方法,并期望它抛出java.util.NoSuchElementException。 Here's my test code: 这是我的测试代码:

@Test(expected = NoSuchElementException.class)
    public void testLineWithoutCommas(){
    String lineToTest = "fdgsdgfdfMarkOwenmark@mark.com";
    List<String> linesToTest = new ArrayList<String>();
    linesToTest.add(lineToTest);

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

Stack trace looks as expected: 堆栈跟踪看起来如预期:

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...

and finally jUnit: 最后是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...

Any ideas what's wrong? 有什么想法有什么不对吗? Thanks for any help. 谢谢你的帮助。

Check you aren't catching and handling the NoSuchElementException somewhere in your code. 检查您是否在代码中的某处捕获并处理NoSuchElementException。 The first stacktrace could be due to your code catching the exception, then logging it, and throwing it as something else, or just trapping it and not throwing it at all. 第一个堆栈跟踪可能是由于您的代码捕获异常,然后记录它,并将其作为其他东西抛出,或者只是捕获它而不是丢弃它。 the 'expected' will only catch exceptions thrown from the test itself, it doesn't deal with exceptions throws and dealt with part way through your code. 'expected'只会捕获从测试本身抛出的异常,它不处理异常抛出并通过代码处理部分方法。

Try it 试试吧

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

@Test
public void testLineWithoutCommas(){

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM