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

1

7

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.

Upcast answered 6/3, 2019 at 10:9 Comment(0)
S
18

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

Inspired by Springs @MockBean, but adapted to Spock semantics

Shift answered 12/3, 2019 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.