【问题标题】:Kotlin Spring WebMvcTest MockkKotlin Spring WebMvcTest Mockk
【发布时间】:2019-09-20 00:19:20
【问题描述】:

有没有人遇到过@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)

【问题讨论】:

    标签: spring-boot testing kotlin mockk


    【解决方案1】:

    发帖3分钟后总能找出答案...

    确保您没有使用 ArgumentMatcher.any() 导入 Mockito 参数匹配器

    【讨论】:

    • 如果您使用 IntelliJ,您可以在项目或 ide 范围内排除 mockito auto importing。即我排除旧的junit包。库之间总是存在命名冲突 :( IntelliJ IDE 允许禁用 IDE 或项目范围内某些包的自动导入和完成。IntelliJ &gt; Preferences &gt; Editor &gt; General &gt; Auto Import &gt; Exclude from auto-import and completition
    【解决方案2】:

    我的问题是 @MockkBean 实际上没有按预期工作(只是创建一个模拟但没有注入它)。我通过在@TestConfiguration 中使用 mockk/spyk 手动覆盖 bean 来解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2022-09-27
      • 2019-10-21
      相关资源
      最近更新 更多