HelloController.javaHat Frühling @GetMapping Arbeit mit MockMvc
@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);
}
}
Die Antwort, die ich hier 404 bekommen, und ich erwarte 200.
Aber es funktioniert und ich bekomme 200, wenn ich @GetMapping zu @RequestMapping (value = "{id}/hallo", Methode ändern = RequestMethod.GET)
Fehle ich hier etwas?
Wie initialisierst du deine 'MockMvc'? –
Ihr Code (und Grundannahmen) funktioniert gut für mich. Bitte poste ein [mcve]. –
@SotiriosDelimanolis Ich habe die Testklasse jetzt aktualisiert.Ich habe nur nicht die Config-Datei enthalten – user3451476