1

我试过搜索任何类似的东西,并尝试了各种解决方案都无济于事。我有一些嵌套测试失败了MockKException: no answer found,即使线程不应该接触另一个测试中使用的模拟,因为我已经用@Isolate.

这是我的类结构:所有 MVC 测试的超类:

@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 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))
                    }
                }
        }

这在大多数情况下都会过去,但会随机导致以下异常:

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)

我疯狂地试图解决这个问题,但没有任何结果,甚至没有提示可能导致它的原因。任何帮助将不胜感激。

4

0 回答 0