我的类无法自动连接UserService - 它会抛出NullPointerException。我想找到一种方法来测试UserValidator类。我不知道如何在ExistingValidationRule类中注入模拟。
public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;
@Override
public void validate(User user, Errors errors) {
service.find(user, errors);
}
}
@Component
public class UserValidator implements Validator {
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
rules.add(new ExistingValidationRule());
for(RegistrationRule<User> rule : rules){
rule.validate(user, errors);
}
}
}
public class UserValidatorTest {
@InjectMocks
private UserValidator userValidator;
@InjectMocks
private ExistingValidationRule existingValidationRule;
@Mock
private UserService service;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testValidUser() throws Exception{
userValidator.validate(createdUser,errors);
}
答案 0 :(得分:0)
class UserValidator
// if all roles that you need are spring beans- then do autowired then by super type
@Autowired
privete Collection<RegistrationRule> roles ;
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
// all spring-bean configured validators were autowired
for(RegistrationRule<User> rule : rules){
rule.validate(user, errors);
}
}
或
@Component
public class UserValidator implements Validator {
//if rules was created before
@Autowired
public void setExistingValidationRule(ExistingValidationRule existingValidationRule){
rules.add(existingValidationRule);
}
@Override
public void validate(Object o, Errors errors) {
User user = (User) o;
for(RegistrationRule<User> rule : rules){
rule.validate(user, errors);
}
}
并尽量避免在方法validate()中添加新的责任 - 比如添加新的验证器。方法验证应该只进行验证,不再是
答案 1 :(得分:0)
@Autowired
是一个Spring注释,除非你用Spring测试运行器运行你的单元测试,否则这不会做任何事情。
然而,Mockito的@InjectMocks
只会为你的田地填充Mocks,只要你提供一个构造函数来到达那些领域。请尝试以下方法:
public class ExistingValidationRule implements RegistrationRule<User> {
@Autowired
private UserService service;
public ExistingValidationRule(UserService service) {
this.service = service;
}
public ExistingValidationRule() {
}
@Override
public void validate(User user, Errors errors) {
service.find(user, errors);
}
}
我添加了第二个空构造函数,让Spring感到高兴。第一个应该为您的单元测试提供技巧。
快乐测试!