title: Mock Spring service in controller test using Spock
body: <p>I am looking for a way to mock a Service bean used in Controller so I can test only controller using MockMvc. But I can't find an easy way to replace real bean with Spock mock. Everything uses spring-boot 1.3.2 version. More details below:</p>
  
  <p>I have a following controller class</p>
  
  <pre><code>@RestController
  @RequestMapping(path = "/issues")
  @AllArgsConstructor(onConstructor = @__(@Autowired))
  public class NewsletterIssueController {
  
    private final GetLatestNewsletterIssueService latestNewsletterIssueService;
  
    @RequestMapping(
      method = RequestMethod.GET,
      path = "/latest"
    )
    public ResponseEntity getLatestIssue() {
      Optional&lt;NewsletterIssueDto&gt; latestIssue = latestNewsletterIssueService.getLatestIssue();
  
      if (latestIssue.isPresent()) {
          return ResponseEntity.ok(latestIssue.get());
      } else {
          return ResponseEntity.notFound().build();
      }
    }
  }
  </code></pre>
  
  <p>And Integration Spock test for this class:</p>
  
  <pre><code>@ContextConfiguration(classes = [Application], loader = SpringApplicationContextLoader)
  @WebAppConfiguration
  @ActiveProfiles("test")
  class NewsletterIssueControllerIntegrationSpec extends Specification {
  
    MockMvc mockMvc
  
    @Autowired
    GetLatestNewsletterIssueService getLatestNewsletterIssueService
  
    @Autowired
    WebApplicationContext webApplicationContext
  
    def setup() {
      ConfigurableMockMvcBuilder mockMvcBuilder = MockMvcBuilders.webAppContextSetup(webApplicationContext)
      mockMvc = mockMvcBuilder.build()
    }
  
    def "Should get 404 when latest issue does not exist"() {
      given:
          getLatestNewsletterIssueService.getLatestIssue() &gt;&gt; Optional.empty() // this won't work because it is real bean, not a Mock
      expect:
          mockMvc.perform(MockMvcRequestBuilders
                  .get("/issues/latest")
                  .contentType(JVM_BLOGGERS_V1)
                  .accept(JVM_BLOGGERS_V1)
          ).andExpect(MockMvcResultMatchers.status().isNotFound())
    }
  
  }
  </code></pre>
  
  <p>I need a way to replace this autowired bean with a Mock/Stub so I can define interactions in 'given' section.</p>