title: Testing Spring MVC with Mockito
body: <p>first of all: I am rather new to Spring.</p>
  
  <p>I have a very simple Spring Boot app with 3 file:
  Main App:</p>
  
  <pre><code>@SpringBootApplication
  public class App 
  {
      public static void main( String[] args )
      {
          SpringApplication.run(App.class, args);
      }
  }
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>@RestController
  public class GreetingsController {
  
      @Autowired
      private SomeService svc;
  
      @RequestMapping("/greeting")
      public String greeting() {
          System.out.println(svc.sayHello());
          return svc.sayHello();
      }
  }
  </code></pre>
  
  <p>And a "Service":</p>
  
  <pre><code>@Service
  public class SomeService {
  
      public String sayHello() {
          return "Hello from the real thing";
      }
  }
  </code></pre>
  
  <p>I now want to write an (integration) test where the service (which in my real application would have some DB connection) is mocked. What I have is this:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @SpringApplicationConfiguration(classes = App.class)
  @WebAppConfiguration
  public class AppTest
  {
      private MockMvc mockMvc;
  
      @Mock
      private SomeService svcMock;
  
      @Autowired
      private WebApplicationContext webApplicationContext;
  
      @Before
      public void setup() throws Exception {
          MockitoAnnotations.initMocks(this);
          Mockito.when(svcMock.sayHello()).thenReturn("Hello from Mock");
          this.mockMvc = webAppContextSetup(webApplicationContext).build();
      }
  
      @Test
      public void run() throws Exception {
          MvcResult res = mockMvc.perform(get("/greeting"))
              .andExpect(status().isOk())
              .andReturn();
          assertEquals("Hello from Mock", res.getResponse().getContentAsString());
      }
  }
  </code></pre>
  
  <p>Unfortunately this test fails because the real service is being used during testing and not my mock service. What am I doing wrong? How can I tell the framework to use the Mock service during testing?</p>
  
  <p>Thanks and regards</p>