Explore Courses Blog Tutorials Interview Questions
0 votes
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();




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();




in your test system you can include a BarFactory like this:


public void testDoFoo() {

  Bar bar = mock(Bar.class);

  BarFactory myFactory = new BarFactory() {

    public Bar createBar() { return bar;}


  Foo foo = new Foo(myFactory);;

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


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

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.7k users

Browse Categories