我正在完成以下教程:
http://docs.spring.io/docs/Spring-MVC-step-by-step/part4.html
我正在尝试测试下面的类中的验证方法:
public class PriceIncreaseValidator implements Validator {
public void validate(Object obj, Errors errors) {
PriceIncrease pi = (PriceIncrease) obj;
if (pi == null) {
errors.rejectValue("percentage", "error.not-specified", null, "Value required.");
}
........
}
下面是我的 JUnit 测试用例:
private PriceIncreaseValidator priceIncreaseValidator;
private PriceIncrease priceIncrease;
private Errors errors;
public void testEmptyPriceIncrease() {
priceIncreaseValidator.validate(priceIncrease, errors); // This is where I get NPE
assertTrue(errors.hasErrors());
}
因此,在 JUnit 测试用例中调用 validate 方法时,我得到了 NPE。 测试和类都编译得很好。
我已经尝试将priceIncrease转换为如下所示的对象,但仍然没有运气:
Object obj = priceIncrease;
//validate
priceIncreaseValidator.validate(obj, errors);
有什么想法吗?
正如你所看到的,我正在尝试测试如果没有设定价格上涨,那么 调用validate时返回错误。
最佳答案
没有实例化任何字段 PriceIncreaseValidator,PriceIncrease,Errors
。
创建这些字段的实例或使用 Spring Autowiring 它们。
要创建Errors
对象,请使用:
Errors 错误 = new BeanPropertyBindingResult(priceIncrease, "priceIncrease");
完整示例
public void testEmptyPriceIncrease() {
PriceIncreaseValidator priceIncreaseValidator = new PriceIncreaseValidator();
PriceIncrease priceIncrease = new PriceIncrease();
Errors errors = new BeanPropertyBindingResult(priceIncrease, "priceIncrease");
priceIncreaseValidator.validate(priceIncrease, errors); // This is where I get NPE
assertTrue(errors.hasErrors());
}
关于java - 测试 validator 方法时,JUnit 测试因 NPE 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21804848/