Java junit 中 assertThat() 的自定义错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23398736/
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
custom error message for assertThat() in junit?
提问by Medya Gh
I was wondering if assertThat() has a way of adding a custom error message ?
我想知道 assertThat() 是否有添加自定义错误消息的方法?
for example in this :
例如在这个:
assertThat(file.exists(), is(equalTo(true)));
I would like to add some custom message, saying which file name doesnt exist
我想添加一些自定义消息,说明哪个文件名不存在
采纳答案by mleonard
I would prefer the following, to avoid the reader believing that you wish to assert that the file name doesn't exist..!
我更喜欢以下内容,以避免读者相信您希望断言文件名不存在..!
assertThat("File name should exist", file.exists(), is(equalTo(true)));
回答by Alexis C.
Use the overloaded assertThat
method
使用重载assertThat
方法
assertThat("File name doesn't exist", file.exists(), is(equalTo(true)));
回答by Guillaume Polet
You may want to simply use the assertTrue()
methods with 2 args:
您可能只想使用assertTrue()
带有 2 个参数的方法:
Assert.assertTrue("File "+file.getAbsoluePath()+"does not exist", file.exists());
回答by chipiik
I prefer this, since one can read it as a sentence: "assert that file 'myFile' exist: myFile exists is true"
我更喜欢这一点,因为人们可以将其理解为一句话:“断言该文件 'myFile' 存在:myFile 存在为真”
assertThat("File '" + myFile + "' exists", myFile.exists(), is(true));
And one gets also readable message with all necessary information when it fails:
当它失败时,还会收到包含所有必要信息的可读消息:
java.lang.AssertionError: File '/blah' exists
Expected: is <true>
but: was <false>
回答by BaptisteM
I use this method :
我用这个方法:
Throwable thrown = catchThrowable(() -> myTestedObject.funtion());
assertThat("Error Message", thrown, isInstanceOf(MyException.class));