我的類不能autowired UserService - 它拋出NullPointerException。我想找到一種方法來測試UserValidator類。我不知道如何在ExistingValidationRule類中注入mock。在新對象中初始化模擬
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);
}
如果使用'new'創建Spring bean實例,它們不再是Spring bean實例,因此Spring不能自動裝配,無法知道該實例是否存在。將ExistingValidationRule實例自動裝入UserValidator。 –
當你的大部分問題被拒絕時,你正在做一些事情來惹惱很多人。也許缺乏作業就是答案。 –