How to write Junit test cases for try catch block

What you will learn here about Junit

  • How to write Junit test cases for try catch block

How to write Junit test cases for try catch block

Please follow the following steps to know, how to write Junit test case for try catch block or I can say to know how to write junit test case for exception.
1)First create a simple maven project and add Junit as well as Mockito dependency which is shown below
maven mockito dependency

Junit dependency

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

Mockito dependency

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
</dependency>

2)Now create a service class which is shown below
junit test for try catch block in spring boot

3)Now create a class which will consume service which is shown below
junit test case for exception

4)Now write a test case for different exceptions which is shown below.
Use Mockito.spy for mocking actual object
USe Mockito.mock for only mocking object
how to write junit test cases for try catch block

You may also like...