spring @GetMapping 是否与 MockMvc 一起工作

Does spring @GetMapping work with MockMvc

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); 
  }
}

我在这里得到的响应是 404,我预计是 200。

但它有效,如果我将 @GetMapping 更改为 @RequestMapping(value="{id}/hello" , 方法=RequestMethod.GET)

我在这里遗漏了什么吗?

你的配置非常简单

@Configuration
@ComponentScan("com.test.controller")
class HelloConfigTest {

它不会隐式或显式地注册任何 Spring MVC 基础结构 bean。

MockMvc 在内部创建一个 TestDispatcherServlet 来测试您的 @Controller class 时,它必须遵循某些默认的 Spring MVC 基础结构类型.

在这些基础设施类型中 HandlerMapping

to be implemented by objects that define a mapping between requests and handler objects.

TestDispatcherSerlet 使用的默认实现是 DefaultAnnotationHandlerMapping(一个旧的 class),它专门寻找 @RequestMapping ,它不会递归地进行元注释查找。因此,您的 @GetMapping 注释方法未找到且未注册为处理程序。

相反,如果您使用 @EnableWebMvc

配置您的应用程序上下文
@Configuration
@ComponentScan("com.test.controller")
@EnableWebMvc
class HelloConfigTest {

Spring 将隐式注册一个 RequestMappingHandlerMapping,它确实为注释层次结构执行此 "recursive" 查找(称为 merging)。由于 @GetMapping 被注释为 @RequestMapping,因此将找到并注册注释的处理程序方法。


至于@InjectMocks,请注意,该字段引用的实例与用于处理MockMvc 对象执行的请求的实例不同。前者由 Mockito 管理,后者由 Spring.