【发布时间】: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