Mockito : how to verify method was called on an object created within a method?

mre picture mre · Mar 23, 2012 · Viewed 572.7k times · Source

I am new to Mockito.

Given the class below, how can I use Mockito to verify that someMethod was invoked exactly once after foo was invoked?

public class Foo
{
    public void foo(){
        Bar bar = new Bar();
        bar.someMethod();
    }
}

I would like to make the following verification call,

verify(bar, times(1)).someMethod();

where bar is a mocked instance of Bar.

Answer

csturtz picture csturtz · Mar 23, 2012

Dependency Injection

If you inject the Bar instance, or a factory that is used for creating the Bar instance (or one of the other 483 ways of doing this), you'd have the access necessary to do perform the test.

Factory Example:

Given a Foo class written like this:

public class Foo {
  private BarFactory barFactory;

  public Foo(BarFactory factory) {
    this.barFactory = factory;
  }

  public void foo() {
    Bar bar = this.barFactory.createBar();
    bar.someMethod();
  }
}

in your test method you can inject a BarFactory like this:

@Test
public void testDoFoo() {
  Bar bar = mock(Bar.class);
  BarFactory myFactory = new BarFactory() {
    public Bar createBar() { return bar;}
  };

  Foo foo = new Foo(myFactory);
  foo.foo();

  verify(bar, times(1)).someMethod();
}

Bonus: This is an example of how TDD can drive the design of your code.