Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use @MockBean annotation while working with Spock framework

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.

like image 607
pannu Avatar asked Mar 06 '19 10:03

pannu


1 Answers

You should use @SpringBean instead of @MockBean. As its javadoc says:

Inspired by Springs @MockBean, but adapted to Spock semantics

like image 184
Dmitry Khamitov Avatar answered Jan 01 '23 09:01

Dmitry Khamitov