0

I wrote few junits, using some mocking techniques. But stucked here:

public class Lookup {
    private LookupMethod lookupMethod;

    private interface LookupMethod {
        String lookup(String input);
    }

   public String treatString(@Nullable String input) {
       ...
       String lookupResult = lookupMethod.lookup(lookupInput);
       ...
   }
}

I'm unit testing the treatString() method and looking how to mock the lookupMethod.lookup() call in the treatString() method above. I can't change Lookup class.

I'll appreciate a tip (example would be even better).

Max
  • 5
  • 6

1 Answers1

0

Basically, this class is super hard to test when you can't modify it.

Using the dark magic of PowerMock it should be possible to mock things by name, meaning that you provide a raw string denoting the method you want to override. See here how to do that.

But as said: that is basically dark magic. It means to add PowerMock to your dependencies. Which will invite others to use PowerMock in the future. Which carries the risk of people writing even more hard to test code. Because you know have a tool that allows you to test that stuff. Instead of writing easy to test code.

And of course: in case someone else changes that class, like renaming that method, then your test breaks.

And then, ask yourself: what is the point of testing a class you aren't supposed to change? What if you find a bug, will it stay in?!

GhostCat
  • 137,827
  • 25
  • 176
  • 248