cancel
Showing results for 
Search instead for 
Did you mean: 

How to mock void private method with argument as Object?

Former Member
0 Kudos

Hello Expert I have below scenario

In public method I have 2 void private method .

In first method I have argument as String In second method I have argument as Object. I JUNIT I call this public method and want to bypass both private method .

I can able to bypass first private method i.e. argument as String By using doNothing().when(demoPrivate, method(DemoPrivate.class, "getFirstNameMethod")).withArguments(fname);

But I cant able to bypass second method i.e. argument as Object. doNothing().when(demoPrivate, method(DemoPrivate.class, "demoPrivateMethod")).withArguments(demoPrivate1);

Please help me on the above issue Regards Ruturaj

Accepted Solutions (1)

Accepted Solutions (1)

former_member387866
Active Contributor
0 Kudos

Hi Rutaraj,

This is a question for StackOverflow, or where you should Google "Unit Testing Best Practices".

Short answer: Change your Unit Tests to test Behaviour.


Long Answer:

Your unit tests should test the behaviour of the public methods, or software modules. Mocking the private tests, you are only testing the implementation. If the implementation changes, they tests will fail, but the behaviour of the method will remain the same. This makes refactoring less of an exact science.

When your public methods call the private methods, you are testing the private methods as part of the public method's behaviour.

If you take a trivial example, a multiply(5, 4) method, it can either call a Calculator class's add(4, 4); method 5 times, or it can use the 5*4 operator.

 public double multiply(double x, double y) {
   return x * y;
 }

Or it can be

 public double multiply(double x, double y) {
   double total = 0;
   for (int i = 0; i < x; i++) {
     total += add(y,y);
   }
   return total;
 }

The behaviour test will always be true: assertEquals(20, multiply(5, 4)).

The implementation test will be tied to the need for the add method to be called Mockito.verify(calculator, times(5)).add();, if the method is refactored to use x * y, the test will need to be rewritten, double work.

Regards,
Luke

Answers (0)