1. Overview
1.概述
In this quick tutorial, we’ll have a look at AssertJ’s exception-dedicated assertions.
在这个快速教程中,我们将看一下AssertJ的异常专用断言。
2. Without AssertJ
2.没有AssertJ
In order to test if an exception was thrown, we’d need to catch the exception and then perform assertions:
为了测试是否有异常被抛出,我们需要捕捉异常,然后执行断言。
try {
// ...
} catch (Exception e) {
// assertions
}
But, what if an exception isn’t thrown? In that case, the test would pass; this is why it’s necessary to fail test cases manually.
但是,如果没有抛出一个异常呢?在这种情况下,测试会通过;这就是为什么有必要手动失败测试案例。
3. With AssertJ
3.用AssertJ
Using Java 8, we can do assertions on exceptions easily, by leveraging AssertJ and lambda expressions.
使用Java 8,我们可以通过利用AssertJ和lambda表达式,轻松地对异常进行断言。
3.1. Using assertThatThrownBy()
3.1.使用assertThatThrownBy()
Let’s check if indexing an out of bounds item in a list raises an IndexOutOfBoundsException:
让我们检查一下,在一个列表中索引一个超界的项目是否会引发IndexOutOfBoundsException:。
assertThatThrownBy(() -> {
List<String> list = Arrays.asList("String one", "String two");
list.get(2);
}).isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageContaining("Index: 2, Size: 2");
Notice how the code fragment that might throw an exception gets passed as a lambda expression.
注意到可能抛出异常的代码片段是如何被作为一个lambda表达式传递的。
Of course, we can leverage various standard AssertJ assertions here like:
当然,我们可以在这里利用各种标准的AssertJ断言,如。
.hasMessage("Index: %s, Size: %s", 2, 2)
.hasMessageStartingWith("Index: 2")
.hasMessageContaining("2")
.hasMessageEndingWith("Size: 2")
.hasMessageMatching("Index: \\d+, Size: \\d+")
.hasCauseInstanceOf(IOException.class)
.hasStackTraceContaining("java.io.IOException");
3.2. Using assertThatExceptionOfType
3.2.使用assertThatExceptionOfType
The idea is similar to the example above, but we can specify the exception type at the beginning:
这个想法与上面的例子类似,但我们可以在开始时指定异常类型。
assertThatExceptionOfType(IndexOutOfBoundsException.class)
.isThrownBy(() -> {
// ...
}).hasMessageMatching("Index: \\d+, Size: \\d+");
3.3. Using assertThatIOException and Other Common Types
3.3.使用assertThatIOException和其他常见类型
AssertJ provides wrappers for common exception types like:
AssertJ为常见的异常类型提供了包装器,如:。
assertThatIOException().isThrownBy(() -> {
// ...
});
And similarly:
而类似的是。
- assertThatIllegalArgumentException()
- assertThatIllegalStateException()
- assertThatIOException()
- assertThatNullPointerException()
3.4. Separating the Exception From the Assertion
3.4.从断言中分离出异常
An alternative way to write our unit tests is writing the when and then logic in separate sections:
另一种编写单元测试的方法是将when和then逻辑写在不同的部分:。
// when
Throwable thrown = catchThrowable(() -> {
// ...
});
// then
assertThat(thrown)
.isInstanceOf(ArithmeticException.class)
.hasMessageContaining("/ by zero");
4. Conclusion
4.结论
And there we are. In this short article, we discussed different ways to use AssertJ for performing assertions on exceptions.
我们就在这里。在这篇短文中,我们讨论了使用AssertJ对异常执行断言的不同方法。
As always, the code relating to this article is available over on Github.
与往常一样,与本文有关的代码可在Github上获得。