I've tried searching anything similar and tried various solutions to no avail.
I have some nested tests which are failing with MockKException: no answer found
, even though threads should not be touching mocks under use in another test, as I've annotated the class with @Isolate
.
Here is my class structure: Superclass for all MVC tests:
@Isolate
@WebMvcTest
@ContextConfiguration(
classes = [
HelloController::class,
WebSecurityConfig::class,
TestApplication::class,
]
)
@EnableConfigurationProperties(AuthProperties::class)
abstract class WebMvcSpecIT: FreeSpec() {
override fun listeners(): List<TestListener> {
return listOf(SpringListener)
}
@Autowired
lateinit var mockMvc: MockMvc
@Autowired
lateinit var objectMapper: ObjectMapper
@MockkBean
lateinit var userService: UserService
override fun beforeTest(testCase: TestCase) {
super.beforeTest(testCase)
TestAuthUtils.logout()
}
override fun afterTest(testCase: TestCase, result: TestResult) {
super.afterTest(testCase, result)
// cannot user clearAllMocks(), as it bleeds into other tests when running multithreaded
clearMocks(
userService,
creativeSearchService,
)
}
Class with test failing:
class HelloControllerSpecIT : WebMvcSpecIT() {
init {
"Should send message that shows user is logged in" - {
(Role.values().toSet() - setOf(Role.ROLE_SERVICE))
.forEach { role ->
"Should send message that shows $role user is logged in" {
// GIVEN User is logged in as $role
loggedInAs("testUser", setOf(role))
every { userService.get("testUser") } returns User(name = "John Doe")
// WHEN user sends hello request
val request = mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
// THEN HTTP 200 response is returned
request.andExpect(MockMvcResultMatchers.status().isOk)
// AND payload contains message
val expected = objectMapper.writeValueAsString(MessageDTO("Hello, John Doe!"))
request.andExpect(MockMvcResultMatchers.content().json(expected))
// AND contentType is for Client
request.andExpect(MockMvcResultMatchers.content().contentType(Constants.V1.clientJson))
}
}
}
And this passes most of the time, but randomly results in the follow exception:
Request processing failed; nested exception is io.mockk.MockKException: no answer found for: UserService(service.UserService#0 bean#34).get(testUser)
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is io.mockk.MockKException: no answer found for: UserService(service.UserService#0 bean#34).get(testUser)
Im going crazy trying to resolve this with no results or even hints as to what could be causing it. Any help will be greatly appreciated.