1

I have to write a unit test for a method like:

void doSomethingWith(Country country) {...}

There are the following classes:

Interface:

public interface Country {
  String getName();
  ... // and a lot of other methods, more than 20
}

Class, implementing the interface:

public class CountryInst implements Country {
  ...
}

For my test I'm choosing between the following options:

1) Pass a mock as a parameter:

Country country = Mockito.mock(Country.class);
Mockito.doReturn("Canada").when(country).getName();
doSomethingWith(country);

2) Or create a new instance of CountryInst and override the needed method:

Country country = new CountryInst {
  @Override
  String getName() {
    return "Canada";
  }
}
doSomethingWith(country);

Which one is preferable?

closed as primarily opinion-based by user40980, GlenH7, durron597, JDT, jwenting Oct 25 '15 at 11:52

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • That's pretty cool, my language doesn't do that. I assume Mockito still has the advantage of being able to make assertions about the call afterwards? – Nathan Cooper Oct 21 '15 at 23:35
3

It largely depends on whether doSomethingWith uses every single field of Country. If yes, then the two approaches would be equivalent and it would be up to you to decide which one is more readable. Otherwise, it's much cleaner to create a mock object that only stubs the methods that are interacted with, leaving out those that are not relevant. This would make it easier to understand what's being tested by clearly stating the given/when/then parts.

Not the answer you're looking for? Browse other questions tagged or ask your own question.