我有以下测试:
@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(...) {
}
对于偶数迭代,我看到一个错误:
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
我试着做
Mockito.reset(connectionPoolSpy, connectionSpy)
在测试结束时,但没有帮助
解决方案正在添加
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
因此测试类定义将如下所示:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
class MyTest {