How to avoid multiple asserts in a JUnit test

What you will learn here about Junit test case

  • How to avoid multiple asserts in a JUnit test

Please click on below link to download Sample project
Sample code for Single Assert replacing multiple asserts (6 downloads)

How to avoid multiple asserts in a JUnit test

Please follow the following steps to know h1
1)First create a maven project

2)Add following dependency in pom.xml file which is shown below

	  <dependency>
	  <groupId>junit</groupId>
	  <artifactId>junit</artifactId>
	  <version>4.13.2</version>
	 </dependency>

Junit pom.xml dependency

3)Create java class whose test case you want to write which is shown below
java class

4)Now please create Test case class

5)Now we will create Helper class which will help us for checking different different operations like equal check or null check which is shown below

How to avoid multiple asserts in a JUnit

6)Now we will use helper class for checking multiple operations and use result of those operations with single assert statement which is shown below
How to avoid multiple asserts in a JUnit test

Commonly Asked Question

1)Is it OK to have multiple asserts in a single unit test?

Answer : It is not good to have multiple asserts in a single unit test case. It’s better to use only one assert statement in single unit test case.

You may also like...