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”,method = RequestMethod.GET),我会得到200
我在这里错过了什么吗?
解决方法:
您的配置非常简单
@Configuration
@ComponentScan("com.test.controller")
class HelloConfigTest {
它不会隐式或显式地注册任何Spring MVC基础结构bean.
当MockMvc在内部创建一个TestDispatcherServlet来测试你的@Controller类时,它必须遵循一些默认的Spring MVC基础结构类型.
这些基础设施类型中有HandlerMapping
to be implemented by objects that define a mapping between requests and handler objects.
TestDispatcherSerlet使用的默认实现是DefaultAnnotationHandlerMapping(一个旧类),它专门查找@RequestMapping,它不会递归地执行元注释查找.因此,找不到@GetMapping带注释的方法,也没有将其注册为处理程序.
相反,如果使用@EnableWebMvc配置应用程序上下文
@Configuration
@ComponentScan("com.test.controller")
@EnableWebMvc
class HelloConfigTest {
Spring将隐式注册一个RequestMappingHandlerMapping,它会对注释层次结构(称为合并)进行“递归”查找.由于@GetMapping使用@RequestMapping进行注释,因此将找到并注册带注释的处理程序方法.
至于@InjectMocks,请注意该字段引用的实例与用于处理MockMvc对象执行的请求的实例不同.前者由Mockito管理,后者由Spring管理.