【发布时间】:2019-04-19 08:56:03
【问题描述】:
测试函数未将预期异常捕获为所需值。它会像错误一样抛出异常。
我试着做
@Rule
ExpectedException thrown = ExpectedException.none();
@Test(expected = UnsupportedOperationException.class)
public void testNotAddingDifferentCurrency(){
Money money1 = new Money("4.43", Locale.GERMANY);
Money money2 = new Money("1.436", Locale.US);
money1.add(money2);
thrown.expect(InvalidBarcodeException.class);
}
和
@Test(expected = UnsupportedOperationException.class)
public void testNotAddingDifferentCurrency() throws UnsupportedOperationException{
Money money1 = new Money("4.43", Locale.GERMANY);
Money money2 = new Money("1.436", Locale.US);
money1.add(money2);
}
但它仍然给出响应:
java.lang.UnsupportedOperationException
at main.Money.add(Money.java:44)
at tests.MoneyTest.testNotAddingDifferentCurrency(MoneyTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code -1
货币类主体:
public Money add(Money other) {
if (!compatibleCurrency(other)) {
throw new UnsupportedOperationException();
}
return new Money(amount.add(other.amount), currency);
}
@Override
public String toString() {
return decimalFormat.format(amount);
}
@Override
public boolean equals(Object o) {
Money money = (Money) o;
if (!amount.equals(money.amount)) return false;
if (!currency.equals(money.currency)) return false;
if (!decimalFormat.equals(money.decimalFormat)) return false;
return true;
}
}
我期待其他类似主题的答案,但答案看起来像我上面的代码。希望有人知道原因。我希望 test 的输出能够通过,但实际输出是 Process finished with exit code -1 in cause of Expection。”
【问题讨论】:
-
这是junit4?你是如何注释测试类的? RunWith ?
-
junit 4.10 和
public class MoneyTest extends TestCase -
某处一定有@Runwith
-
你想用你的规则实现什么?在 JUnit 4 中,将预期的异常添加到
@Test注释就足够了。而且您的主要课程主体不完整。 -
您的堆栈跟踪显示您正在使用 JUnit38ClassRunner,所以我认为这使您运行与 JUnit3 相同。由于您没有显示完整的测试类,我们看不出为什么要使用这个运行器。
标签: java testing exception junit