java - JUnit:测试异常不起作用(AssertionError:即使抛出异常,也是预期的异常)

标签 java exception testing junit assert

我正在尝试测试我的类是否有异常。我尝试了几种不同的方法,但没有任何效果。我在这里做错了什么?

我正在尝试测试的类,PrimeNumber.java:

public class PrimeNumber {

    static final Logger LOG = LogManager.getLogger("Log");

    private String primeNumberStr;

    public PrimeNumber(String primeNumberStr) {
        this.primeNumberStr = primeNumberStr;
    }

    public String getPrimeResult() {
        String resultStr = "";
        try {
            // Convert user input to int
            int primeNumberInt = Integer.parseInt(primeNumberStr);
            // Beginning of return message
            resultStr += primeNumberInt + " is ";
            // Add "not" if it's not a prime
            if (!Primes.isPrime(primeNumberInt))
                resultStr += "NOT ";
            // End return message
            resultStr += "a prime";
            // If not a valid number, catch
        } catch (NumberFormatException e) {
            // Log exception
            LOG.warn("NumberFormatException" + e.getMessage());
            // If empty user input
            if (primeNumberStr.length() == 0)
                resultStr += "No number inserted";
            // Else not empty but not valid
            else
                resultStr += primeNumberStr + " is not a valid number";
            resultStr += ". Only numbers without decimals are accepted.";
        }

        return resultStr;
    }

}

现在我尝试测试的事情:

带注释

@Test(expected = NumberFormatException.class)
public void testNumberFormatExceptionBeingThrown() {
    PrimeNumber primeNumber = new PrimeNumber("6dg");
    primeNumber.getPrimeResult();
}

导致测试失败并且:

java.lang.AssertionError: Expected exception: java.lang.Exception

使用 JUnit 规则:

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

@Test(expected = NumberFormatException.class)
public void testNumberFormatExceptionBeingThrown() {
    thrown.expect(NumberFormatException.class);
    thrown.expectMessage("For input string: \"a21\"");
    PrimeNumber primeNumber = new PrimeNumber("a21");
    primeNumber.getPrimeResult();
}

结果:

java.lang.AssertionError: Expected test to throw (an instance of java.lang.NumberFormatException and exception with message a string containing "For input string: \"a21\"")
at org.junit.Assert.fail(Assert.java:88)
at org.junit.rules.ExpectedException.failDueToMissingException(ExpectedException.java:263)
at org.junit.rules.ExpectedException.access$200(ExpectedException.java:106)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:245)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

最佳答案

一切都按预期进行。您已经成功地防止您的方法抛出异常。您已经成功地测试了它们是否抛出异常。

只是,同时做这两件事是没有意义的。 您需要决定在给定错误参数时是否希望每个方法抛出异常。

如果您希望方法在给出错误参数时抛出异常,则不要捕获并处理该异常,只需让它被抛出即可。然后,测试您的方法是否抛出该异常,就像上面所做的那样。

如果您不希望该方法在给出错误参数时抛出异常,请决定您希望它做什么。然后,测试您的方法是否符合您的要求。如果抛出异常,测试将失败。


也就是说,您在类(class)中处理数字的方式没有多大意义。您将它们作为 String 获取,将它们存储为 String,并将它们作为 String 返回,但是每当您使用它们时,您可以将它们来回转换为 int。为什么不一开始就在所有地方使用 int 呢?

关于java - JUnit:测试异常不起作用(AssertionError:即使抛出异常,也是预期的异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822206/

相关文章:

ruby-on-rails - 使用环境变量的 Rails 单元测试装置抛出 MySQL 错误

Java 序列化。不同的引用

java - 在运行时寻找新的 Java 类

scala try/catch 没有捕获一些异常

python: 如何使用 TO、CC 和 BCC 发送邮件?

Maven 错误 - 包 org.junit 不存在

java - Java ME

java - Java中int转String的高效方法

.net - FormatException 未处理 vb.net

c# - 使用 Process.Start : Firefox not starting when you set Usename and Password 启动 Firefox