要将Hamcrest与JUnit 4一起使用,我们使用一个assertThat()函数.但是,JUnit 5不再具有assertThat()功能.如何在没有Hamcrest的情况下使用assertThat()?
我有一个提供Restriction-object 的特定方法(在哪里Restriction是一个接口).由于它的实现已经是测试,我只想测试我的方法是否实际上提供了一个对象RestrictionImpl.
我看到有一些我可以assertThat和它一起使用的匹配器,我想,匹配器isA是想要完成这项任务的东西.
简化我的代码看起来像这样:
public static Restriction getRestriction() {
return new RestrictionImpl();
}
Run Code Online (Sandbox Code Playgroud)
我的测试看起来像那样;
@Test
public void getRestriction_returnsRestrictionImpl() {
assertThat(getRestriction(), isA(RestrictionImpl.class));
}
Run Code Online (Sandbox Code Playgroud)
但是这不会编译.我所能做的就是测试,如果a RestrictionImpl是Restriction......但是没有必要这样做.
我误解了目的isA吗?它的意义是什么?
更新:
使用assertThat(getRestriction(), is(instanceOf(RestrictionImpl.class)))会工作,但我认为这isA是一个快捷方式.以我想要的方式
打电话assertThat需要它有签名assertThat(T, Matcher<? extends T>),但它的签名是assertThat(T, Matcher<? super T>)
我正在使用 R 的assertthat 包,并且希望(暂时)在断言失败时输出警告而不是错误。使用assertthat 包最简单的方法是什么?
我意识到想要警告而不是错误有点违背了断言的用途。从长远来看,我们确实希望在断言失败时输出错误。从短期来看,我们仍然希望代码即使在输入错误的情况下也能运行,因为输入错误的输出目前仍然“足够好”。
一个简单的例子:假设我有一个函数,将 x 作为输入并输出 x+5。如果 x!=3 我想输出警告。由于我们最终将使用assert_that,因此如果我们可以使用assertthat 包来发出警告,那就太好了。
从长远来看,我们将使用这个:
> x <- 3
> fn <- function(x) {assert_that(x==3); return(x+5)}
> fn(3)
[1] 8
> fn(4)
Error: x not equal to 3
Run Code Online (Sandbox Code Playgroud)
从短期来看,这是我迄今为止最好的:
> fn <- function(x) {if(!see_if(x==3)) warning(validate_that(x==3)); return(x+5)}
> fn(3)
[1] 8
> fn(4)
[1] 9
Warning message:
In fn(4) : x not equal to 3
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我正在寻找更简洁的解决方案(最好的情况是将“output_warning”参数传递给assert_that,但我认为不存在)。