当前位置:网站首页>Exception assertion of assertj
Exception assertion of assertj
2022-06-10 05:29:00 【HoneyMoose】
This page mainly talks about AssertJ Exception assertion for .
summary
In this quick navigation , We are mainly here to talk about AssertJ It's abnormal (exception) Assertion .
of AssertJ Project , Please visit AssertJ / Fluent assertions for java page .

Don't use AssertJ
If not used AssertJ, We need to catch an exception first , Then make assertions in the exception .
For example, the following pseudo code , We caught an exception , And then judge .
try {
// ...
} catch (Exception e) {
// assertions
}
however , If the program does not throw an exception during execution , In the above use case , The test will pass .
In order for assertions to be executed , Why do we need to manually trigger an exception ?
Use AssertJ
stay Java 8 Later versions , We can do that by using AssertJ and lambda expression , It's very easy to assert exceptions .
Use assertThatThrownBy() Method
Let's see what the following code will throw IndexOutOfBoundsException abnormal :
This is because we define a List Is the length of the 2 , But we have a line of code that will access List Of the 3 Elements , The above code must throw an exception .
assertThatThrownBy(() -> {
ArrayList<String> myStringList = new ArrayList<String>(Arrays.asList("Strine one", "String two"));
myStringList.get(2);
}).isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("Index 2");
Note that the code snippet above may throw a lambda Expression exception .
Of course , We can also use AssertJ To provide a chained assertion , That's why we don't use Junit Reason for self assertion .
.hasMessageStartingWith("Index 2")
.hasMessageContaining("2")
.hasMessageEndingWith("length 2")
.hasMessageContaining("Index 2")
.hasNoCause();
Use assertThatExceptionOfType Method
This method is similar to the method used above , Because we know that the execution of this program will throw an exception , So we specify exceptions at the very beginning of the program :
assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> {
int numerator = 10;
int denominator = 0;
int quotient = numerator / denominator;
})
.withMessageContaining("/ by zero");
The above method , Because we used 0 Divisor , So an exception must be thrown .
We asserted this exception at the very beginning of the program .
Use assertThatIOException And other common types
AssertJ in the light of Some common exceptions are wrapped , You can use these wrapped exceptions directly :
assertThatIOException().isThrownBy(() -> {
// ...
});
And other similar exceptions :
- assertThatIllegalArgumentException()
- assertThatIllegalStateException()
- assertThatIOException()
- assertThatNullPointerException()
Detach exceptions from assertions
Optional , We can separate exceptions from assertions .
The way to separate is to add one when and then Logical segment :
// when
Throwable thrown = catchThrowable(() -> {
int numerator = 10;
int denominator = 0;
int quotient = numerator / denominator;
});
// then
assertThat(thrown).isInstanceOf(ArithmeticException.class)
.hasMessageContaining("/ by zero");
}
The above code first throws an exception , Then, assert and judge the thrown exception .
Conclusion
In this essay , We are right. AssertJ How to make exception assertions is briefly introduced , It also discusses AssertJ How to make exception assertions .
边栏推荐
- In R language, GLM is used to build logistic regression model, and the relationship model between multiple covariates and grouped variables is built to calculate, estimate and predict propensity score
- Interview question 08.01 Three step problem
- 自定义Tooltips提示气泡Js插件
- 微信手机端js小游戏踩方块源码
- With the advent of the digital wave, how to achieve agile business delivery and sustainable technology governance? Uncover the ant bizstack
- Talk about the recent situation
- Personnaliser le plug - in bulles JS prompt tooltips
- Interview question 05.06 Integer conversion
- MTK基于GAT工具和SpOffineDebugSuite工具 dump 抓取和解析
- The R language catools package divides the data, randomforest package constructs the random forest model, and views the basic information output by the model (number of trees, estimation error outside
猜你喜欢
Redis specifies the configuration file startup, database related instructions, and redis operation string and list types
![[Linux < day20 >] - An Introduction to database and container technology](/img/d1/23dfe81887181d76f0c9bb3172341d.png)
[Linux < day20 >] - An Introduction to database and container technology

JS wechat games - fighting mosquitoes

The world's first financial chart database test benchmark project was approved, and ant group opened patent Co Construction

Some beautiful JS prompt boxes

One to one copy of core board system image using USB flash disk

Zen project management flow

最高奖项!2022数博会领先科技成果“新技术”授予OceanBase数据库

In terms of emotional perception, the financial assistant robot "zhixiaobao" goes further

Flutter DIO example
随机推荐
顺序查找、二分查找
LeetCode326-3的幂-数学
[nick] intensive reading
Custom tooltips prompt bubble JS plug-in
2022.6.1-----leetcode. four hundred and seventy-three
The R language uses the matchit package for propensity matching analysis and match The data function constructs the matched sample set, and judges the balance of all covariates in the sample after pro
In terms of emotional perception, the financial assistant robot "zhixiaobao" goes further
photoClip. JS mobile image upload and interception plug-in
Understand ant bizstack cloud native development and governance platform
BFS practice topic
2022.6.3-----leetcode. eight hundred and twenty-nine
联系人二维码生成插件qrcode.js
Pytorch: sub model parameter freezing + BN freezing
An analysis of DuPont analysis: the financial situation of East China Construction Group Co., Ltd
Three technical solutions of ant group were selected as "typical solutions for it application innovation in 2021"
Hevc HM learning 01
In the kernel_ init,_ Role in exit
The process of data division with R language's catools package, random forest model construction with randomforest package, and visualization of the trained random forest model with plot function (the
Interview question 08.07 Permutation without duplicate strings
Interview question 05.06 Integer conversion
https://www.ossez.com/t/assertj-exception/13988