I have following test:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@WebAppConfiguration
class MyTest {
@MockitoSpyBean
protected lateinit var ldapConnectionPoolHolder: LdapConnectionPoolHolder
@BeforeEach
fun setup() {
connectionPoolSpy = spy(ldapConnectionPoolHolder.getConnectionPool())
doReturn(connectionPoolSpy).whenever(ldapConnectionPoolHolder).getConnectionPool()
connectionSpy = spy(connectionPoolSpy.getConnection()) // this line leads to error sometimes
doReturn(connectionSpy).whenever(connectionPoolSpy).getConnection()
}
@ParameterizedTest("...")
@MethodSource("withoutCookiesSuccessScenarios")
fun myTest(...) {
}
for even iterations I see an error:
java.lang.IllegalArgumentException: Please don't pass mock here. Spy is not allowed on mock.
at org.mockito.Mockito.spy(Mockito.java:2246)
at org.mockito.kotlin.SpyingKt.spy(Spying.kt:52)
enter code here
I tried to do Mockito.reset(connectionPoolSpy, connectionSpy)
in the end of the test but it doesn't help
The solution is adding
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
So test class definition will look like:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class MyTest {