4

I have a strange behavior of @SpyBean field in my integration tests. For example, I have a few integration tests:

package a;

@SpringBootTest
public class A {
 @SpyBean
 public MySpyBeanCandidate spyBean;

 @Test
 public void test1 {
   // some work
   Mockito.verify(spyBean, Mockito.atLeastOnce()).methodName(eq("String value"), anyString());
 }

}
package a;

@SpringBootTest
public class B {
 @SpyBean
 public MySpyBeanCandidate spyBean;

 @Test
 public void test2 {
   // some work
   Mockito.verify(spyBean, Mockito.atLeastOnce()).methodName(eq("String value"), anyString());
 }

}

The problem is when I try to execute them separately they executed successfully, but if I'll run them together, in the second test Mockito.verify(..) will throw an exception: Wanted but not invoked. But I have debugged it and checked that method (methodName) called correctly. Who knows why this is happening?

Danzis
  • 83
  • 6
  • It's hard to say you don't provide enough code. Is the method really called as expected when both are run? The test setup and production code is missing. – DCTID Jan 17 '20 at 03:47
  • @DCTID, thanks for the response! "Is the method really called as expected when both are run?", yes and in the second method ```spyBean``` it's really mock, but nothing doesn't happen, just ```Wanted but not invoked```. "The test setup and production code is missing." - what do you mean? It's the correct code. – Danzis Jan 17 '20 at 14:11
  • Try to provide an [mre]. As it is currently we can not tell you what is going wrong as we are not able to reproduce this behaviour based on the code you have posted. – second Jan 17 '20 at 16:06
  • What I mean by the test setup and production code is missing is, `MySpyBeanCandidate` is not supplied. You're spying so the actual code is important. Also, you just wrote `//some work` for however you call, mock etc the `spyBean`. We couldn't copy paste you code into our ide and see the same results that you are. – DCTID Jan 17 '20 at 23:17
  • Did you ever figure this out? I am having the same issue. – Ryan Quinn May 04 '20 at 21:14

2 Answers2

2

@DirtiesContext on each @Test method for such cases worked for me.

Artyom
  • 161
  • 1
  • 10
0

For me helped the next lines:

    @AfterEach
    public void resetSpy() {
        reset(spyBean);
    }

From the documentation:

the mock forgot any interactions and stubbing

Anton Sych
  • 71
  • 1
  • 3