title: Spring boot @SpyBean causing test suite to error probably due to issue with context not being reset
body: <p>I have an issue with a spring integration test. </p>
  
  <p>The behavior:</p>
  
  <ul>
  <li><p>When I run the test below in isolation, it is in success. </p></li>
  <li><p>However, when all tests are run, many of them including the one below are in error.</p></li>
  <li><p>When I ignore the test below and run all test, all are in success.</p></li>
  </ul>
  
  <p>I haven't included the error stacktrace because it is highly related to our business logic and I suspect the error is related to my usage of spring boot test <code>@SpyBean</code>.</p>
  
  <p>Here is the test:</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @ActiveProfiles(profiles = "test")
  @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
  
  ...
  
  @Autowired
  private TestRestTemplate restTemplate;
  
  @Autowired
  private DataKeyStore dataKeyStore;
  
  @SpyBean
  private TokenTools tokenTools;
  
  ...
  
  @Test
  public void myTest() throws Exception {
  
     doReturn("someGeneratedToken")
          .doReturn("someGeneratedToken")
          .doCallRealMethod()
          .when(tokenTools)
          .createToken(any(TokenProfile.class), anyString(), anyString());
    ...
  </code></pre>
  
  <p>Please note that <code>DataKeyStore</code> is a dependency of <code>TokenTools</code>.</p>
  
  <p>As I said above, I suspect tests are stepping on each other and my <code>@SpyBean</code> somehow leaks on other test classes...</p>
  
  <p>My question is how can I make sure this test does not step on the other tests? I have tried the <code>@DirtiesContext</code> annotation to no avail...</p>
  
  <p>Also what puzzles me is that the <code>@SpyBean</code> is already reset (as per the documentation/javadoc).</p>
  
  <p>Can anyone please help?</p>
  
  <p><strong>edit</strong>: Using my IDE to debug the tests indicates that <code>TokenTools</code> is instantiated only twice for all tests: once at the initialization of tests and a second time for creating the <code>@SpyBean</code> for the test above. The remainder of tests run after the test above use the second instance i.e. the <code>@SpyBean</code> instance...</p>