0

Void methods and Mockito in Java

When we talk about unit tests, we think about input values and return values to/from methods. Returned values are checked against expected values as a way to verify behavior of codes. But how would you test codes that do not return any values? Essentially, we resort to stubbing out void methods. That is easy in Mockito!

Software Requirements

  1. Java 7
  2. Eclipse Luna
  3. Mockito 2.0.2-beta
  4. JUnit 4.12
  5. Maven

Codes to Test

Below is a sample class with a single void method. The main behavior of the codes processes PersonRecord objects conditionally – if status is “UNDERAGED”, use service.processUnderAged(…) method; otherwise, use service.processLegalAged(…). There are also null-checkings at the start of the void method.

The Unit Tests

PersonRecord with null id

If id is null, the method returns immediately and no codes executed except PersonRecord.getdId(). We did not even use the service code.

PersonRecord with “1000” id and null status

Now PersonRecord.id is not null but status is. The codes still invoked getId() but returns false. The getStatus is invoked because of the OR condition in the if statement. Each of these methods were called once. The service codes remained unused.

PersonRecord with “1000” id, and “LEGALAGED” status

Both getId() and getStatus() were used. getStatus() was used for the second time to compare its value against “UNDERAGED”. Only processLegalAged(…) was invoked on the service object.

PersonRecord with “1000” id, and “UNDERAGED” status

Both getId() and getStatus() were used. getStatus() was used for the second time to compare its value against “UNDERAGED”. Only processUnderAged(…) was invoked on the service object.

PersonRecord with “1000” id and other status

Status that is neither “UNDERAGED” or “LEGALAGED”, use processLegalAged(…)

Download the Codes

https://github.com/Turreta/VoidMethodsAndMockito