Writing functionality is the main focus whenever we are writing a software program, but it is equally important that we make sure our code works the way we intended it to. And how do we do that? By writing unit test cases. They are used to test the smallest functionality of code. Unit test cases are an essential part of software development. In this blog, we are going to cover one of the testing scenarios in which we will be writing Unit test cases for void functions with Mockito.

How to Test void methods

As we already know that our aim is to test void methods in a class but it is also really important to understand why do we test void methods.

Whenever we write unit test cases for any method we expect a return value from the method and generally use assert for checking if the functions return the value that we expect it to return, but in the case of void methods, they do not return any value. So how do we check if our method is functioning properly? Let’s see using an example.

In this example, we are creating Two classes Information and Publishing.

The Information class looks like this:

public class Information {

   private final Publishing publishing;

   public Information(Publishing publishing) {
       this.publishing = publishing;
   }

   public void sendInfoForPublishing(Person person) {
       publishing.publishInformation(person);
   }
}

As we can see the method sendInformationForPublishing() is a void method. The logic for the method is simple. It takes a Person object as a parameter and passes the object to the method of Publishing class.

The method publishInformation() is also a void method.

public class Publishing {

   public void publishInformation(Person person) {
       System.out.println(person);
   }
}

Let us now see how we can write unit test cases for this simple implementation.

#testing #junit #programming #developer

Unit Testing Void Methods with Mockito and JUnit
40.40 GEEK