2

I have code like this:

class Outer {
  private External external;
  class MyCallback extends ExternalAbstractCallback {
    void somethingHappened() { if (super.someCondition()) { ... }; }
  }

  public Outer() {
     external = ...;
  }

  public setExternal(External e) { external = e; } // test support

  public void doIt() {
    external.setCallback(new MyCallback());
    external.doSomething();
  }
}

I want to test the behavior of MyCallback when doIt() is called. I use Mockito to create a mock External and can then get external.doSomething() to execute the MyCallback.somethingHappened. Can I control the return value of the call to super.someCondtion at line 4? Can I rearrange the implementation to improve testability? The implementations of External and ExternalAbstractCallback cannot be changed.

kevin cline
  • 2,608
  • 2
  • 25
  • 38

1 Answers1

3

Your problem is that you can't mock new with Mockito. In a nutshell, code that you want to test should never call new.

Workarounds:

  • Add a getter/setter for the callback.
  • Move new MyCallback() into a new protected helper method which you override in your test
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820