Shamseer
Shamseer

Reputation: 692

Unit testing void methods in Java Junit/Mockito

I see similar questions, but not answered properly as I am looking for.

I have void method, which does some changes to the Model object as per the some other DB Values then save it again back to DB.

Pseudo code:

User{
List<Mark> marks;
String fullName;
int grade;
date dob;
}

The logic is to update User grade by applying some formulas by calling another service.

This is how I designed to test it:

I can give the User object with marks as input. I will mock the Service by providing the formula to determine the grades as per the marks. I want to test the final User Object is matching with what I am expecting just before saving.

I know that I can move that to separate method and return the object so that can be unit tested. What I am looking here is if there any way to test the logic inside a void method to verify the updated object. I have several methods like that in our project.

I know there is Mockito.verify or I can call like doNothing etc. This is just to call method and see what is happening inside. But I am not getting no data verification is possible by calling those methods.

It could be great if any one can suggest a solution for this.

I gave an example what the code is available for me. This is generic question though. My question is here how can I test a void method? My question is not how to mock a void method. Since void method does not return anything, but it does some logic and finally it updates DB. I want to test whether the implemented logic is working for different scenarios. The situation is cannot change the original method-writing a unit testing for those methods. Any suggestions?

Upvotes: 0

Views: 2271

Answers (1)

haggisandchips
haggisandchips

Reputation: 542

The fact your method doesn't return anything is irrelevant. You test a void method same as any other method: setup your inputs, invoke the method, perform required assertions.

If I understand correctly, the issue you are experiencing is that the method does not return anything but as you are passing in the initial User object you already have a reference to the object so you can still perform whatever assertions you need to AFTER the void method completes.

Upvotes: 1

Related Questions