【发布时间】:2014-04-30 21:58:49
【问题描述】:
我想知道 assertThat() 是否可以添加自定义错误消息?
例如在这个:
assertThat(file.exists(), is(equalTo(true)));
我想添加一些自定义消息,说明哪个文件名不存在
【问题讨论】:
我想知道 assertThat() 是否可以添加自定义错误消息?
例如在这个:
assertThat(file.exists(), is(equalTo(true)));
我想添加一些自定义消息,说明哪个文件名不存在
【问题讨论】:
我更喜欢以下内容,以避免读者认为您希望断言文件名不存在..!
assertThat("File name should exist", file.exists(), is(equalTo(true)));
【讨论】:
使用重载的assertThat方法
assertThat("File name doesn't exist", file.exists(), is(equalTo(true)));
【讨论】:
我更喜欢这个,因为可以把它读成一句话:“assert that file 'myFile' exists: myFile exists is true”
assertThat("File '" + myFile + "' exists", myFile.exists(), is(true));
当它失败时,它也会获得包含所有必要信息的可读消息:
java.lang.AssertionError: File '/blah' exists
Expected: is <true>
but: was <false>
【讨论】:
您可能只想使用带有 2 个参数的 assertTrue() 方法:
Assert.assertTrue("File "+file.getAbsoluePath()+"does not exist", file.exists());
【讨论】:
我用这个方法:
Throwable thrown = catchThrowable(() -> myTestedObject.funtion());
assertThat("Error Message", thrown, isInstanceOf(MyException.class));
【讨论】: