Mockito Spy Test

I use Mockito to write tests for code. However, I adhere to the following scenario - Class A has 2 methods, method1 () and method2 (). I tried using ArgumentCaptor to catch the values โ€‹โ€‹sent to method (). But, since I use @Spy, I can not use Matchers.

How to check method1 ()?

class A{ B b; method1(arg1, arg2){ //some logic method2(arg1, arg2, ....argN); } method2(arg1, arg2,....argN){ //some logic b.method3(arg1, arg2...); } } 

How to verify that method2 gets the same argument values? The following class of tests I wrote:

 Class TestA{ @Mock B b; @Spy @InjectMocks //required else b is null A a = new A(); @Test public void testMethod1(){ a.method1(arg1, arg2); //How to verify method2 receives same argument values (arg1, arg2)???? //verify(a, times(1)).method2(.......); } 

}

+6
source share
3 answers

I was intrigued by this post and the comments posted by @David, so I decided to code a working example for those who follow me.

 /* * class to test */ public class A { public void methodA(String str) { this.methodB(str); } protected void methodB(String str) { // some implementation } } 

We want to state that the value passed to method B () is what we expect. Reading on an ArgumentCaptor led me to discover the equivalent Captor annotation

 import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MultipleMethodCallTest { @Spy A a = new A(); @Captor ArgumentCaptor<String> captor; @Test public void captureSecondMethodCallArgument() throws Exception { // EXPECTED String greeting = "hello world"; // PERFORM TEST a.methodA(greeting); // ASSERT verify(a).methodB(captor.capture()); assertEquals(greeting, captor.getValue()); } } 

This example has been tested with

  • Mockito-all-1.8.5.jar
  • JUnit-4.8.2.jar
+8
source

You cannot verify it by calling method b method3. If your arguments to method2 do not affect method 3, can the args thesis be useless at all ?!

+3
source

You can use matches with spies; it works great. I donโ€™t know why you thought you couldnโ€™t.

I took your source code and edited it to compile it. Then I added a call to MockitoAnnotations.initMocks - you need this to create a spy and layout, and enter a layout (unless you use MockitoJUnitRunner , which makes initMocks for you). I again put verify on the call to method2 . This worked fine.

So, contrary to Omnaest's answer, you do not need to use B method3 to verify this. I suspect your only problem was that you forgot initMocks .

Good luck with this, and feel free to post if you need more help.

+2
source

Source: https://habr.com/ru/post/913978/


All Articles