HelloController.java
@RestController
class HelloController {
@GetMapping(value = "{id}/hello")
public ModelAndView listAPI(@PathVariable("id") String profileId) {
ModelAndView mav = new ModelAndView();
return mav;
}
}
HelloControllerTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = HelloConfigTest.class)
class HelloControllerTest {
@Inject
private WebApplicationContext webApplicationContext;
@Inject
private Foo mockFoo
@InjectMocks
HelloController helloController;
private MockMvc mockMvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testHello() throws Exception {
mockMvc.perform(
get("/{id}/campaigns", "id1"))
.andExpect(status().isOk()));
}
}
// I have another test that directly calls the controller method.
// So I need @InjectMocks to get an instance of the controller
@Test
public void test2() {
when(mockFoo.getX()).thenReturn(true);
helloController.saveAPI();
}
HelloConfigTest.java
@Configuration
@ComponentScan("com.test.controller")
class HelloConfigTest {
@Bean
public mockFoo() {
return Mockito.mock(Foo.class);
}
}
The response that I get here is 404 and I expect 200.
But it works and I get 200 if I change @GetMapping to @RequestMapping(value="{id}/hello", method=RequestMethod.GET)
Am I missing anything here ?