Reset Mockito Spy

I have a test class (based on TestNG) where I use Mockito.verify for a spy object.

It works:

 public class Program { @Spy private TestObject testObject; @Test public void test1() { testObject.makeSth(); verify(testObject, only()).someMethodNeedToBeChecked(); } } 

But here:

 public class Program { @Spy private TestObject testObject; @Test public void test1() { testObject.makeSth(); verify(testObject, only()).someMethodNeedToBeChecked(); } @Test public void test2() { // Some different scenario testObject.makeSth(); verify(testObject, only()).someMethodNeedToBeChecked(); ... } } 

I get a Mokito exception, I have more than one call to someMethodNeedToBeChecked . Of course, I tried to add Mockito.reset(testObject) , but that didn't help me at all.

How can I reset a spy object if I need to test the same method in several tests?

+7
source share
1 answer

From the Mockito documentation:

Reset mocks (Starting with version 1.8.0)

Smart Mockito users are unlikely to use this feature because they know that this may be a sign of poor tests. Usually you do not need to reset your layouts, just create new layouts for each testing method. Instead of reset (), please consider writing simple, small, and focused testing methods for lengthy, excessive tests. The first potential smell of the reset () code is in the middle of the test method. This probably means that you are testing too much. Follow the whisper of your testing methods: "Please keep us small and focused on solitary behavior." There are several threads about this on the mockito mailing list.

The only reason we added the reset () method is to let us work with layouts embedded in the container.

You should probably just recreate the spy in @BeforeMethod :

 public class Program { private TestObject testObject = new TestObject(); private TestObject spyTestObject; @BeforeMethod public void buildSpy() { spyTestObject = spy(testObject); } @Test public void test1() { spyTestObject.makeSth(); verify(spyTestObject , only()).someMethodNeedToBeChecked(); } @Test public void test2() { // Some different scenario spyTestObject.makeSth(); verify(spyTestObject , only()).someMethodNeedToBeChecked(); ... } } 
+12
source

All Articles