我很惊讶地发现,在运行/调试单元测试时,IntelliJ实际上会对IDEA中的@NotNull进行运行时验证。我能否将相同的功能添加到我的maven构建中呢?(我需要哪些jars/jvm设置?)
public aspect ValidationAspect {
private final Validator validator;
{
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
pointcut serviceMethod() : execution(public * com.yourcompany**.*(..));
before() : serviceMethod(){
final Method method = (Method) thisJoinPoint.getTarget();
for(final Object arg : thisJoinPoint.getArgs()){
if(arg!=null) validateArg(arg,method);
}
}
private void validateArg(final Object arg, final Method method) {
final Set<ConstraintViolation<Object>> validationErrors = validator.validate(arg);
if(!validationErrors.isEmpty()){
final StringBuilder sb = new StringBuilder();
sb.append("Validation Errors in method ").append(method).append(":\n");
for (final ConstraintViolation<Object> constraintViolation : validationErrors) {
sb.append(" - ").append(constraintViolation.getMessage()).append("\n");
}
throw new RuntimeException(sb.toString());
}
}
}
有一个与IntelliJ功能密切相关的Maven插件,目前位于https://github.com/osundblad/intellij-annotations-instrumenter-maven-plugin。它在CrazyCoder的回答中首次提到,在IDEA-31368票下讨论。
你可以在 JUnit 测试中进行注释验证。
import java.util.Set;
import javax.validation.ConstraintViolation;
import junit.framework.Assert;
import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
public class Temp {
private LocalValidatorFactoryBean localValidatorFactory;
@Before
public void setup() {
localValidatorFactory = new LocalValidatorFactoryBean();
localValidatorFactory.setProviderClass(HibernateValidator.class);
localValidatorFactory.afterPropertiesSet();
}
@Test
public void testLongNameWithInvalidCharCausesValidationError() {
final ProductModel productModel = new ProductModel();
productModel.setLongName("A long name with\t a Tab character");
Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel);
Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1);
}
}
如果你的选择是Spring,那就来看看这些Spring单元测试。
@org.junit.Test(expected = NullPointerException.class)
测试? - Martin