Kotlin Spring WebMvcTest模拟

时间:2019-09-20 00:19:20

标签: spring-boot testing kotlin mockk

有人遇到@MockkBean似乎无法正常工作或至少存根未通过的问题吗?

简单的例子:

@RunWith(SpringRunner::class)
@WebMvcTest(controllers = [WidgetController::class])
class WidgetTest {

    @Autowired
    private lateinit var mockMvc: MockMvc
    @MockkBean
    private lateinit var widgetService: WidgetService

    @Test
    fun test() {
        val value = objectMapper.readValue<MyWidget>(something()))
        every {
            widgetService.getWidget(ArgumentMatchers.anyString())
        } returns value


        mockMvc
                .perform(
                        get(
                                "/apis/widget/v1/widget"
                        ).contentType(MediaType.APPLICATION_JSON)
                )
                .andExpect {
                    JSONAssert.assertEquals(
                           widgetPayload(),
                            it.response.contentAsString,
                            false
                    )
                }
    }
}

导致:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is io.mockk.MockKException: no answer found for: WidgetService(com.bondhouse.pms.services.externalportfolios.ExternalPortfoliosService#0 bean#1).getWidget(test)

1 个答案:

答案 0 :(得分:0)

总是在发帖后三分钟找出答案...

确保不使用ArgumentMatcher.any()

导入Mockito参数匹配器。