Aequitas
Aequitas

Reputation: 2265

Ignoring argument

So I'm trying to test a method methodUnderTest which is something like this:

methodUnderTest{
    //Other stuff that works nice
    this.setterMethod(OtherClass.methodThatErrors(arg1));
}

So I'm trying to avoid that static method call methodThatErrors.

What I'm doing so far:

ClassUnderTest spy = Mockito.spy(objectOfClassUnderTest);
Mockito.doNothing().when(spy).setterMethod(Mockito.any(OtherClass.class));

However this does not work, the method is still being called. I would've thought that it shouldn't call the argument method at all because I've written any for the argument of setterMethod. So how can I prevent this call using Mockito, not PowerMockito.

Edit:

So I managed to mock it by moving the static method call like so:

methodUnderTest{
    this.extraSetterMethod(arg1);
}

extraSetterMethod(arg1){
    this.setterMethod(OtherClass.methodThatErrors(arg1));
}

I don't really like this solution because it's adding several extra lines of code (even more with javadoc) which just makes the class messier.

Upvotes: 0

Views: 414

Answers (1)

Makoto
Makoto

Reputation: 106389

The problem here is that the value is coming directly from the static method, and not the setter itself. Whatever value it's getting is coming from the real invocation of the method itself. Mocking out the call to the setter has no effect; it's not the result of the setter that's in error.

This is a scenario in which you have to make a hard decision:

  • Introduce a parameter to the method so that the call can be easier to mock, or
  • Use PowerMockito to mock out the call.

I strongly encourage the latter, especially if you're dealing with a legacy code base which is not very forgiving to a signature change.

Upvotes: 1

Related Questions