Testing Spring MVC DAO using Mockito Spring TestContext Framework

Testing Spring MVC DAO using Mockito Spring TestContext Framework

Any enterprise application you work unit testing is mandatory part of it. In this tutorial we will keep focus on doing our unit testing using both popular framework Mockito and Spring TestContext framework. Both framework is good to complete independent unit testing easily. To give brief idea first we will create sample Spring MVC application which will consist of Controller –> Service –> DAO(Getting data from database). Below is final maven project structure:

Note: You could visit previous tutorial to get started with Mockito: Complete unit test using Mockito

Testing Spring MVC DAO using Mockito Spring TestContext Framework

As you see above we call sequence goes to Controller –> Service –> DAO layer. To keep tutorial short I will just show you classes which has been used (If you want to take look interface please download complete project from the bottom link).

  • Dependency in pom.xml:

  • Controller class:

  • PersonServiceImpl.java ( We will test only one method selectAllPerson where call goes to the database and fetches all person data):

  • PersonDAOImpl.java: (One one method implementation has been done selectAllPerson):

  • Test controller class where Spring TestContext framework used:

  • To run above unit test right click above class –> Run As –> JUnit you will see data from database as below:

Testing Spring MVC DAO using Mockito Spring TestContext Framework

  • Another unit test class for controller using Mockito framework:

  • Run this test as JUnit you will see below:

Testing Spring MVC DAO using Mockito Spring TestContext Framework

  • That’s it.

download  Download project: SpringMVCTestingMockito

Leave a Reply

Your email address will not be published. Required fields are marked *