I was trying out Spock and encountered an interesting problem when writing controller-tests.
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())
}
}
So the problem is mocking method on SomeService
instance does not work because it uses a different Mock class for mocking the instance of SomeService
class. I got a work around using the static Mock method from Spock in the setup and then using a setter to set SomeService
in the controller. My question is there any elegant way to use @MockBean
with Spock Specification
testing.