简体   繁体   English

使用JUnit assertEquals的自定义异常消息?

[英]Custom exception message using JUnit assertEquals?

I'm using assert equals to compare two numbers 我正在使用断言等于比较两个数字

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

Then, when I generate the Test Report I get 然后,当我生成测试报告时,我得到了

"My error message expected (First) was (Second)" “我预期的错误信息(第一) (第二)”

How can I customize the part I've put in italic? 如何自定义我用斜体显示的部分? And the format of the numbers? 和数字的格式?

You can use something like this: 你可以使用这样的东西:

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);

The message is hard-coded in the Assert class. 消息在Assert类中进行了硬编码。 You will have to write your own code to produce a custom message: 您必须编写自己的代码才能生成自定义消息:

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

(Note: the above is a rough example - you'll want to check for nulls etc. See the code of Assert.java to see how it's done). (注意:上面是一个粗略的例子 - 你需要检查空值等。请参阅Assert.java的代码以了解它是如何完成的)。

Thanks to your answer I've found in the Assert class this 感谢您的回答,我在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 + ">";
}

I guess I can't modify Junit Assert class, but I can create a new class in my project with the same name, just changing format, am I right? 我想我不能修改Junit Assert类,但是我可以在我的项目中创建一个具有相同名称的新类,只是改变格式,我是对的吗? Or I can just change format in my class and it will affect the Exception thrown? 或者我可以在我的课程中更改格式,它会影响抛出的异常?

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

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