【问题标题】:Custom exception message using JUnit assertEquals?使用 JUnit assertEquals 的自定义异常消息?
【发布时间】:2013-05-13 14:37:03
【问题描述】:

我正在使用断言等于来比较两个数字

Assert.assertEquals("My error message", First , Second);

然后,当我生成测试报告时,我得到了

“我的错误消息 预期(第一次)(第二次)”

如何自定义我以斜体显示的部分?以及数字的格式?

【问题讨论】:

  • 我假设您使用的是 Java。如果是Scala,请相应调整标签。

标签: java testing junit customization


【解决方案1】:

你可以这样使用:

int a=1, b=2;
String str = "Failure: I was expecting %d to be equal to %d";
assertTrue(String.format(str, a, b), a == b);

【讨论】:

  • 这不会改善这种情况。 OP 已经知道如何添加错误消息,但目标是更改斜体部分的措辞。您的解决方案仍将保留措辞。
  • 你确定吗?使用 (2,1) 在 Eclipse 上运行我只得到“失败:我期望 2 等于 1”,而不是“预期......是”部分......
  • @Salem 那是因为您使用的是 assertTrue,而不是 assertEquals
【解决方案2】:

消息被硬编码在Assert 类中。您必须编写自己的代码来生成自定义消息:

if (!first.equals(second)) {
  throw new AssertionFailedError(
      String.format("bespoke message here", first, second));
}

(注意:上面是一个粗略的例子——您需要检查空值等。请参阅Assert.java 的代码以了解它是如何完成的)。

【讨论】:

    【解决方案3】:

    感谢您的回答,我在 Assert 类中找到了这个

            static String format(String message, Object expected, Object actual) {
        String formatted= "";
        if (message != null && !message.equals(""))
            formatted= message + " ";
        String expectedString= String.valueOf(expected);
        String actualString= String.valueOf(actual);
        if (expectedString.equals(actualString))
            return formatted + "expected: "
                    + formatClassAndValue(expected, expectedString)
                    + " but was: " + formatClassAndValue(actual, actualString);
        else
            return formatted + "expected:<" + expectedString + "> but was:<"
                    + actualString + ">";
    }
    

    我想我不能修改 Junit Assert 类,但我可以在我的项目中创建一个具有相同名称的新类,只是改变格式,对吗?或者我可以在我的类中更改格式,它会影响抛出的异常?

    【讨论】:

    • 是的,您可以采用这种方法。这基本上就是我在回答中的建议 - 如果您需要更改消息,则必须编写自己的代码来进行测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多