0

Say I have a class like this:

public class Foo {
    private Bar bar;
    public Foo(Bar bar) {
        this.bar = bar;
    }

    public void someMethod() {
        bar.someOtherMethod();
    }
}

How would I verify that bar.someOtherMethod() is called once when someMethod() is called? In my test, I am passing in a mocked Bar class into the constructor.

My test looks something like this:

private Bar bar;
private Foo foo;

@Before
public void setUp() throws Exception {
    bar = mock(Bar.class);
    foo = new Foo(bar);
}

@Test
public void testSomeMethod() {
    foo.someMethod();
    verify(Bar).someOtherMethod();
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
Will Huang
  • 325
  • 7
  • 15
  • The error you describe is not conducive with the solution (it is as described by karth500). Could you post your test code too so that we could be sure that you're passing in a mock? – Makoto May 06 '15 at 01:22

2 Answers2

2

With Mockito -

verify(mockBar, times(1)).someOtherMethod();
karth500
  • 21
  • 2
0

Since you're passing in the instance of Bar, it's relatively straightforward:

  • Interact with the mock (i.e. you have to expect that the mock does something (or nothing, in this case)
  • Expect that it was interacted with exactly once

With that, you can employ something like this in your test:

doNothing().when(mockBar).someOtherMethod();
foo.someMethod();
verify(mockBar).someOtherMethod();
Makoto
  • 104,088
  • 27
  • 192
  • 230