对于我创建的这个MovieForm类:
public class MovieForm {
private String movieName;
@Min(1)
@Max(31)
@NotNull
private Integer maxNumberOfTickets;
}
我创建了这个单元测试来测试我的表单的验证注释。
public class MovieFormTest {
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeClass
public static void createValidator() {
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@AfterClass
public static void close() {
validatorFactory.close();
}
@Test
public void form_test() {
MovieForm form = new MovieForm();
form.setMaxNumberOfTickets(null);
Set<ConstraintViolation<MovieForm>> violations = validator.validate(form);
Assert.assertFalse(violations.isEmpty());
ConstraintViolation<MovieForm> violation = violations.iterator().next();
Assert.assertEquals("may not be null", violation.getMessage());
form.setMaxNumberOfTickets(32);
violations = validator.validate(form);
Assert.assertFalse(violations.isEmpty());
violation = violations.iterator().next();
Assert.assertEquals("must be less than or equal to 31", violation.getMessage());
form.setMaxNumberOfTickets(0);
violations = validator.validate(form);
Assert.assertFalse(violations.isEmpty());
violation = violations.iterator().next();
Assert.assertEquals("must be greater than or equal to 1", violation.getMessage());
form.setMaxNumberOfTickets(15);
violations = validator.validate(form);
Assert.assertTrue(violations.isEmpty());
}
但是这个测试只适用于我在我的pom中添加这个glassfish依赖项
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b08</version>
</dependency>
否则我得到 HV000183:无法初始化&#39; javax.el.ExpressionFactory&#39;。错误。但是我的同事并不希望我使用这种依赖,因为我们正在使用WebSphere,所以我的问题是:有没有办法让这个单元测试工作而不必使用那个依赖?
答案 0 :(得分:0)
在测试范围
中创建具有此依赖关系的maven配置文件(如Alayor在其评论中建议的那样)<profiles>
<profile>
<id>validation-test</id>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b08</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
启用此配置文件运行测试。 如果需要使用任何其他实现测试新的配置文件
当然,在构建阶段,您需要添加一些相应的validation-api或使用WebSphere实现作为依赖关系,如果部署到具有impl的容器,则使用<scope>provided</scope>
。