【问题标题】:Is there a way to use @MockBean annotation while working with Spock framework有没有办法在使用 Spock 框架时使用 @MockBean 注释
【发布时间】:2019-07-27 23:05:49
【问题描述】:

我在尝试 Spock 并在编写控制器测试时遇到了一个有趣的问题。

WebMvcTest(value = SomeController.class)
@AutoConfigureMockMvc
@ActiveProfiles(value = "restapi")
@Import(value = SecurityConfiguration)
class AccountBalanceControllerTest extends Specification {

@Autowired
SomeController someController

@MockBean
SomeService someService

def "lets test it" {
  given: 
      someService.findAllByName(_) >> ["Some", "Work"]
  when:
    def response = mockMvc.perform(get("/v1/someName/545465?fast=false").with(user("mvc-test").roles("SOME_ACCOUNTS")))
  then: 
      response.andExpect(status().isOk()) 
}


}

所以问题是 SomeService 实例上的模拟方法不起作用,因为它使用不同的 Mock 类来模拟 SomeService 类的实例。我在设置中使用 Spock 的静态 Mock 方法解决了问题,然后使用 setter 在控制器中设置 SomeService。我的问题是有什么优雅的方式来使用 @MockBean 和 Spock Specification 测试。

【问题讨论】:

    标签: spring-boot spock spring-test-mvc


    【解决方案1】:

    您应该使用@SpringBean 而不是@MockBean。正如它的 javadoc 所说:

    受 Springs @MockBean 启发,但适应 Spock 语义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2013-11-13
      • 2021-12-18
      • 2022-08-14
      相关资源
      最近更新 更多