01: JUnit with Mockito step by step

Step 1: Create a simple maven project say “code-quality”

Step 2: Import into eclipse.

#1. Validator code & unit testing

Step 3: Validator interface & implementation

Step 4: Write a unit test to test the “ValidatorImpl.java”. Run as junit test.

#2. SalaryDao code & unit testing

Step 5: SalaryDao interface & implementation.

Step 6: Write a unit test to test the “SalaryDaoImpl.java”. Run as junit test.

#3. SalaryService code & unit testing

Step 7: SalaryService interface & implementation.

Step 8: Write a unit test to test the “SalaryServiceImpl.java”. Run as junit test.

Was SalaryServiceTest really a unit test?

No. It was more like an integration test. It tests both “SalaryDaoImpl” and “ValidatorImpl” as well since SalaryServiceImpl depends on “SalaryDao” and “Validator”. If we need to only test the logic for “SalaryServiceImpl” in isolation we need to mock “SalaryDaoImpl” and “ValidatorImpl” as shown below.

Mockito into action

Step 9: Update pom.xml file to include the “Mockito” library and also upgrade the junit version to 4.12.

Step 10: Revised “SalaryServiceTest” that mocks “SalaryDaoImpl” and “ValidatorImpl”.


Why & What are the benefits

🎯 Why java-success.com?

🎯 What are the benefits of Q&As approach?

Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.

800+ Java & Big Data Q&As Menu

Top