Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a void method with Mockito

Tags:

java

mockito

I have a method like this:

public void someMethod() {
  A a = new A(); // Where A is some class.
  a.setVar1(20);
  a.someMethod();
}

I want to test 2 things:

  1. The value of Var1 member variable of a is 20.
  2. someMethod() is called exactly once.

I have 2 questions:

  1. Are those test objectives correct or should I be testing something else ?
  2. How exactly do I test this using Mockito ?
like image 774
Shan Avatar asked Aug 19 '26 11:08

Shan


2 Answers

You can't test that using Mockito, because Mockito can't access a local variable that your code creates and then let go out of scope.

You could test the method if A was a injected dependency of your class under test, or of the method under test

public class MyClass {
    private A a;

    public MyClass(A a) {
        this.a = a;
    }

    public void someMethod() {
        a.setVar1(20);
        a.someMethod();
    }
}

In that case, you could create a mock A, then create an instance of MyClass with this mock A, call the method and verify if the mock A has been called.

With your code, as it is, the only way to test the code is to verify the side effects of calling someMethod() on an A with var1 equal to 20. If A.setVar1() and A.someMethod() don't have any side-effect, then the code is useless: it creates an object, modifies it, and forgets about it.

like image 148
JB Nizet Avatar answered Aug 22 '26 02:08

JB Nizet


Use JB Nizet's advice but note that order is important to you:

When verifying and order is important, use:

A mock = mock(A);

new MyClass(mock).someMethod();

InOrder order = inOrder(mock);
order.verify(mock).setVar1(20);
order.verify(mock).someMethod();

(Testing for exactly one invocation is the default in mockito).

Caution

This kind of test will be tightly coupled to the implementation. So do this in moderation. In general aim for testing state rather than implementation where possible.

like image 36
weston Avatar answered Aug 22 '26 00:08

weston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!