我正在尝试使用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
测试。
你应该使用@SpringBean而不是@MockBean
。正如其javadoc所说:
受Springs @MockBean的启发,但适应了Spock的语义