Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

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.

1 Answer

0 votes
by (46k points)

Dependency Injection

If you add the Bar situation or a factory that is used for building the Bar situation (or one of the other 483 ways of preparing this), you'd access necessary to do complete the test.

Factory Example:

Presented a Foo class composed 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 system you can include 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();

}

Tip: This is an illustration of how TDD can make the purpose of your code.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...