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.
You should use @SpringBean instead of @MockBean
. As its javadoc says:
Inspired by Springs @MockBean, but adapted to Spock semantics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With