Software Development

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!

[wp_ad_camp_5]

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.

[wp_ad_camp_4]

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(…)

[wp_ad_camp_3]

Download the Codes

https://github.com/Turreta/VoidMethodsAndMockito

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like