我有一个自定义的ConstraintValidator:
@Component
public class FooValidator implements ConstraintValidator<FooAnnotation, String> {
@Inject
private FooRepository fooRepository;
@Override
public void initialize(FooAnnotation foo) {
}
@Override
public boolean isValid(String code, ConstraintValidatorContext context) {
Foo foo = fooRepository.findByCode(code);
//My code
}
}
在我的Junit测试和MockMVC中,我调用了url,但fooRepository bean验证器始终为null。
我如何在测试控制器中注入它?我试图创建一个模拟存储库,但它也是null。 我的源代码测试:
public class FooControllerTest {
@InjectMocks
private FooController fooController;
private MockMvc mockMvc;
@Before
public void setup() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(fooController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
}
@Test
public void testSave() throws Exception {
Foo foo = new Foo();
// given
//My code...
// when
// then
// with errors
this.mockMvc.perform(post("/foo/update")
.param("name", "asdfasd")
.sessionAttr("foo", foo))
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("foo", "name"));
}
}
答案 0 :(得分:-1)
除了其他方面,您还应该在测试中添加@ContextConfiguration。