til*_*ias 22 java exception assertj
如何使用assertJ 检查自定义异常中的特定字段值?
这是异常类:
public class SomeException extends RuntimeException {
private final Set<Integer> something;
public SomeException (String message, Set<Integer> something) {
super(message);
this.something = something;
}
public Set<Integer> getSomething() {
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
assertThatThrownBy(() -> service.doSomething())
.isInstanceOf(SomeException.class)
.hasMessageStartingWith("SomeException has 1,2,3,4 in something field. I want assert that")
. ??? check that SomeException.getSomething() has 1,2,3,4 ???
Run Code Online (Sandbox Code Playgroud)
问题是,如果我链接extracting() ,它会认为我正在使用Throwable。所以我无法提取字段内容
更新:
SomeException throwable = (SomeException) catchThrowable(() -> service.doSomething(
assertThat(throwable)
.hasMessageStartingWith("extracting() bellow still think we're working with Throwable")
.extracting(SomeException::getSomething <<<--- doesn't work here)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过以下建议,如下所示:
assertThat(throwable)
.hasMessageStartingWith("Works except containsExactlyInAnyOrder()")
.asInstanceOf(InstanceOfAssertFactories.type(SomeException.class))
.extracting(SomeException::getSomething)
.->>>containsExactlyInAnyOrder<<<--- Not working!!!
Run Code Online (Sandbox Code Playgroud)
但我不能再使用containsExactlyInAnyOrder () :(
请指教
jam*_*nna 25
看起来您正在寻找catchThrowableOfType,它可以让您收到正确的课程:
import static org.assertj.core.api.Assertions.catchThrowableOfType;
SomeException throwable = catchThrowableOfType(() -> service.doSomething(), SomeException.class);
assertThat(throwable.getSomething()).isNotNull();
Run Code Online (Sandbox Code Playgroud)
Joe*_*ola 16
有很多变体extracting,您想要使用的是extracting(String),例如:
assertThatThrownBy(() -> service.doSomething())
.isInstanceOf(SomeException.class)
.hasMessageStartingWith("SomeException ... ")
.extracting("something")
.isEqualTo(1,2,3,4);
Run Code Online (Sandbox Code Playgroud)
用于extracting(String, InstanceOfAssertFactory)获取专门的断言,因此如果该值是一个集合,您可以尝试:
assertThatThrownBy(() -> service.doSomething())
.isInstanceOf(SomeException.class)
.hasMessageStartingWith("SomeException ... ")
.extracting("something", InstanceOfAssertFactories.ITERABLE)
.contains();
Run Code Online (Sandbox Code Playgroud)
您还可以尝试:hasFieldOrPropertyWithValue
更新:工作示例
SomeException throwable = new SomeException("foo", Sets.newSet(1, 2, 3, 4));
assertThat(throwable).hasMessageStartingWith("fo")
.extracting("something", InstanceOfAssertFactories.ITERABLE)
.containsExactly(1, 2, 3, 4);
Run Code Online (Sandbox Code Playgroud)