Categories: Unit Testing

Junit & Mock Framework Mockito Code Samples – Part 1

The article represents code samples for Junit tests and Mockito, a mocking framework. In addition, it describes different aspects of unit testing and mocking.

Software Requirement

The goal is to create a simple piece of software which caters to the requirement of school admission where in applicants submit their admission application.

 

Class Design & JUnit Tests

To meet above requirement, following different component is designed:

  • Core Components (Key Ones)
    • AdmissionApplication.java: Consists of method recordNewApplication which validates the submitted application, and later, stores in the database after successful validation.
    • ApplicationValidation.java: Consists of methods for validating business rules associated with admission such as mandatory inputs (first name, last name, class, gender, date of birth etc)
    • AdmissionApplicationDAO.java: Stores the data into database
  • Junit Tests
    • AdmissionApplicationTest: Junit tests for testing AdmissionApplication methods
    • ApplicationValidationTest: Junit tests for testing ApplicationValidation methods

 

Source Code: AdmissionApplication.java

public class AdmissionApplication {

 private AdmissionApplicationDAO admissionApplicationDao;
 private ApplicationValidation applicationValidation;

 public AdmissionApplication() {  
 }

 public ApplicationResult recordNewApplication( Applicant applicant ) {
  ApplicationResult result = null;

  result = applicationValidation.validate( applicant ); 
  if( !result.isSuccess() ) {
   return result;
  } 

  result = admissionApplicationDao.persist(applicant);

  if( result.isSuccess() ) {
   result.setMessage( "Admission application successful" );
  } else {
   result.setMessage( "Admission application failed" );
  }

  return result;
 }

 public AdmissionApplicationDAO getAdmissionApplicationDao() {
  return admissionApplicationDao;
 }

 public void setAdmissionApplicationDao(
   AdmissionApplicationDAO admissionApplicationDao) {
  this.admissionApplicationDao = admissionApplicationDao;
 }

 public ApplicationValidation getApplicationValidation() {
  return applicationValidation;
 }

 public void setApplicationValidation(ApplicationValidation applicationValidation) {
  this.applicationValidation = applicationValidation;
 }
}

 

Source Code (Junit with Mocking): AdmissionApplicationTest.java

In the source code below, following points should be noted:

  1. @Mock annotation is used to represent classes/components whose mocks will be used
  2. Once you annotated mock components, MockitoAnnotations.initMocks(this) is used to initialize these mocks. The code could be seen inside setUp() method.
  3. Mockito.when(…).thenReturn(…): It is used for stubbing. Once stubbed, the method will always return stubbed value regardless of how many times it is called.
  4. Mockito.verify(…).methodName(..): It is used to verify the method invocation.

The important point to note is that mocks have been created for two objects such as ApplicationValidation, and AdmissionApplicationDAO. That implies that code of AdmissionApplication is tested in isolation by mocking dependent classes.

public class AdmissionApplicationTest {

 private AdmissionApplication aa;
 @Mock
 private ApplicationValidation appValidation;
 @Mock
 private AdmissionApplicationDAO aaDao;

 @Before
 public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  aa = new AdmissionApplication();   
  aa.setApplicationValidation( appValidation );
  aa.setAdmissionApplicationDao( aaDao );

 }

 @After
 public void tearDown() throws Exception {
  aa = null;
  appValidation = null;
  aaDao = null;
 }

 @Test
 public void applicationSuccessfulIfAllDetailsGiven() {
  Applicant applicant = new Applicant();    
  ApplicationResult result = new ApplicationResult();
  result.setSuccess( true );

  Mockito.when( appValidation.validate(applicant) ).thenReturn( result );
  Mockito.when( aaDao.persist(applicant)).thenReturn( result );

  result = aa.recordNewApplication( applicant );
  assertTrue( result.isSuccess() );
 }

 @Test
 public void applicationFailureIfValidationFailed() {
  Applicant applicant = new Applicant();    
  ApplicationResult result = new ApplicationResult();
  result.setSuccess( false );
  Mockito.when( appValidation.validate(applicant) ).thenReturn( result );

  result = aa.recordNewApplication( applicant );

  Mockito.verify(appValidation).validate(applicant);
  Mockito.verify(aaDao, Mockito.never()).persist(applicant);
  assertFalse( result.isSuccess() );
 }

 @Test
 public void applicationFailureIfDBPersistenceFailed() {
  Applicant applicant = new Applicant();    
  ApplicationResult result = new ApplicationResult();

  result.setSuccess( true );
  Mockito.when( appValidation.validate(applicant) ).thenReturn( result );
  result.setSuccess( false );
  Mockito.when( aaDao.persist(applicant) ).thenReturn( result );

  result = aa.recordNewApplication( applicant );
  assertFalse( result.isSuccess() );
 }

}

 

Latest posts by Ajitesh Kumar (see all)
Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

Share
Published by
Ajitesh Kumar

Recent Posts

What are AI Agents? How do they work?

Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…

2 weeks ago

Agentic AI Design Patterns Examples

In the ever-evolving landscape of agentic AI workflows and applications, understanding and leveraging design patterns…

2 weeks ago

List of Agentic AI Resources, Papers, Courses

In this blog, I aim to provide a comprehensive list of valuable resources for learning…

2 weeks ago

Understanding FAR, FRR, and EER in Auth Systems

Have you ever wondered how systems determine whether to grant or deny access, and how…

3 weeks ago

Top 10 Gartner Technology Trends for 2025

What revolutionary technologies and industries will define the future of business in 2025? As we…

3 weeks ago

OpenAI GPT Models in 2024: What’s in it for Data Scientists

For data scientists and machine learning researchers, 2024 has been a landmark year in AI…

3 weeks ago