[英]JUnit “expected” doesn't seem to work
我有一個奇怪的問題,我試圖測試一個方法,並期望它拋出java.util.NoSuchElementException。 這是我的測試代碼:
@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));
}
堆棧跟蹤看起來如預期:
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...
有什么想法有什么不對嗎? 謝謝你的幫助。
檢查您是否在代碼中的某處捕獲並處理NoSuchElementException。 第一個堆棧跟蹤可能是由於您的代碼捕獲異常,然后記錄它,並將其作為其他東西拋出,或者只是捕獲它而不是丟棄它。 'expected'只會捕獲從測試本身拋出的異常,它不處理異常拋出並通過代碼處理部分方法。
試試吧
@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.