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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16524712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:18:44  来源:igfitidea点击:

Custom exception message using JUnit assertEquals?

javatestingjunitcustomization

提问by Lorm

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?

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

回答by Duncan Jones

The message is hard-coded in the Assertclass. You will have to write your own code to produce a custom message:

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

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.javato see how it's done).

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

回答by Salem

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

回答by Lorm

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? Or I can just change format in my class and it will affect the Exception thrown?

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