我正在为带有 spting boot 的控制器编写一个单元@WebMvcTest
。
使用@WebMvcTest
,我将能够注入MockMvc
如下所示的对象:-
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@WebMvcTest
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void my_controller_test() throws Exception {
mockMvc.perform(post("/create-user"))
.andExpect(status().isCreated());
}
}
在控制器中,我Principal
使用 spring 注入一个参数HandlerMethodArgumentResolver
。请告诉我如何使用 编写单元测试MockMvc
,以便我可以Principal
在控制器方法中注入一个模拟对象作为参数。
部分 Auto -configured Spring MVC tests解释了带有注释的测试@WebMvcTest
将扫描HandlerMethodArgumentResolver
. 所以我创建了一个 bean,它扩展HandlerMethodArgumentResolver
并返回模拟Principal
对象,如下所示。
@Component
public class MockPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(Principal.class);
}
@Override
public Object resolveArgument(MethodParameter parameter...) throws Exception {
return new MockPrincipal();
}
}
但是参数仍然MockPrincipal
没有传递给控制器方法。
春季启动版本:- 1.4.5.RELEASE