Categories: Unit Testing

Unit Testing with JUnit & Mockito – Code Examples

The article presents quick code example for doing unit testing with JUnit & Mockito mocking framework. It also represents unit testing naming convention where features text is used for naming the test methods thereby representing test class as alternate documentation for the class under test.

Following is done while defining Mock member variables

  • Use @Mock annotation ahead of member variable definitions

Following are steps done in the setup method:

  • Initialize the mock using MockitoAnnotations.initMocks(this);
  • Object of class under test is initialized with the mock objects

Following steps are used in each of the unit test methods:

  • Create/Initialize required objects for working with mocks and methods under test
  • Set the mock behavior on dependent objects
  • Execute the method under test
  • Perform assertions
  • Verify the program execution path by checking on whether a method is invoked or not

The code below represents the class under test and the unit test written to test the class. Take a look the unit test names which represents the card creation function and the scenarios in which it would pass or fail. Following are names. These are unlike the unit test names which uses the function name with state and execution result. I find it easy to understand the unit tests in this way.

  1. cardIsNotCreatedIfMandatoryUserDetailsNotProvided
  2. cardIsNotCreatedIfCardFailedToPersistInDatabase
  3. cardIsCreatedIfAllBusinessRulesAreSatisfied

 

Class Under Test

 

public CPResult createCard( Card card ) {

 CPResult cpResult = new CPResult();

 if( card != null ) {
  boolean validated = cdValidator.validate( card );
  if( validated ) {
   boolean cardCreated = cardDAO.createCard( card );
   if( !cardCreated ) {     
    cpResult.setMessage( CPResult.CARD_PERSISTENCE_FAILURE_MESSAGE );
   }
  } else {    
   cpResult.setMessage( CPResult.CARD_VALIDATION_FAILURE_MESSAGE );
  }
 } else {   
  cpResult.setMessage( CPResult.CARD_FATAL_ERROR_MESSAGE );
 }
 if( cpResult.getMessage() != null ) {
  cpResult.setStatus( CPResult.CARD_OPERATION_FAILURE );
 }
 return cpResult;  
}

 

Unit Test Class

 

public class PrepaidCardProcessorTest {

 private PrepaidCardProcessor prepaidCP; 
 @Mock private CardDetailsValidator cdValidator;
 @Mock private CardDAO cardDAO;

 @Before
 public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  prepaidCP = new PrepaidCardProcessor();
  prepaidCP.setCdValidator( cdValidator );
  prepaidCP.setCardDAO( cardDAO );
 }

 @After
 public void tearDown() throws Exception {
 }

 @Test
 public void cardIsNotCreatedIfMandatoryUserDetailsNotProvided() {
  // Create required objects for working with mocks and methods under test
  //
  Card card = new Card();  
  // Set the mock behavior on dependent objects
  //
  Mockito.when( cdValidator.validate( card ) ).thenReturn( false );
  // Execute the method under test 
  //
  CPResult cpresult = prepaidCP.createCard( card );
  // Perform assertions
  //
  assertTrue( cpresult.getStatus() == CPResult.CARD_OPERATION_FAILURE );
  assertTrue( cpresult.getMessage().equals( CPResult.CARD_VALIDATION_FAILURE_MESSAGE ) );
  // Verify the program execution path by checking on whether a method is invoked or not
  //
  Mockito.verify(cdValidator).validate(card);
  Mockito.verify(cardDAO, Mockito.never() ).createCard( card );
 }

 @Test
 public void cardIsNotCreatedIfCardFailedToPersistInDatabase() {
  // Create required objects for working with mocks and methods under test
  //
  Card card = new Card();  
  // Set the mock behavior on dependent objects
  //
  Mockito.when( cdValidator.validate( card ) ).thenReturn( true );
  Mockito.when( cardDAO.createCard( card ) ).thenReturn( false );
  // Execute the method under test 
  //
  CPResult cpresult = prepaidCP.createCard( card );
  // Perform assertions
  //
  assertTrue( cpresult.getStatus() == CPResult.CARD_OPERATION_FAILURE );
  assertTrue( cpresult.getMessage().equals( CPResult.CARD_PERSISTENCE_FAILURE_MESSAGE ) );
  // Verify the program execution path by checking on whether a method is invoked or not
  //
  Mockito.verify(cdValidator).validate(card);
  Mockito.verify(cardDAO ).createCard( card );
 }

 @Test
 public void cardIsCreatedIfAllBusinessRulesAreSatisfied() {
  // Create required objects for working with mocks and methods under test
  //
  Card card = new Card();  
  // Set the mock behavior on dependent objects
  //
  Mockito.when( cdValidator.validate( card ) ).thenReturn( true );
  Mockito.when( cardDAO.createCard( card ) ).thenReturn( true );
  // Execute the method under test 
  //
  CPResult cpresult = prepaidCP.createCard( card );
  // Perform assertions
  //
  assertTrue( cpresult.getStatus() == CPResult.CARD_OPERATION_SUCCESS ); 
  assertNull( cpresult.getMessage() );
  // Verify the program execution path by checking on whether a method is invoked or not
  //
  Mockito.verify(cdValidator).validate(card);
  Mockito.verify(cardDAO ).createCard( card );
 }

}

[adsenseyu1]

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

Retrieval Augmented Generation (RAG) & LLM: Examples

Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…

1 week ago

How to Setup MEAN App with LangChain.js

Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…

2 weeks ago

Build AI Chatbots for SAAS Using LLMs, RAG, Multi-Agent Frameworks

Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…

2 weeks ago

Creating a RAG Application Using LangGraph: Example Code

Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…

3 weeks ago

Building a RAG Application with LangChain: Example Code

The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…

3 weeks ago

Building an OpenAI Chatbot with LangChain

Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…

3 weeks ago