Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 317
mre Avatar asked Mar 23 '12 15:03

mre


People also ask

How do you verify a method called in Mockito?

Mockito verify only method call If we want to verify that only one method is being called, then we can use only() with verify method.

How do you check if a method is called in Java?

While you can replace it with blank == true , which will work fine, it's unnecessary to use the == operator at all. Instead, use if (blank) to check if it is true, and if (! blank) to check if it is false.

Does Mockito verify use equals?

Internally Mockito uses Point class's equals() method to compare object that has been passed to the method as an argument with object configured as expected in verify() method. If equals() is not overridden then java. lang.


1 Answers

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(Test Driven Development) can drive the design of your code.

like image 144
csturtz Avatar answered Sep 20 '22 11:09

csturtz