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
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With