Unit / Integration Testing the Bean Validation (JSR-303) 集成测试BEAN验证

22 篇文章 0 订阅
3 篇文章 0 订阅

Unit / Integration Testing the Bean Validation (JSR-303)

First you will need to load both: the Bean Validation andELSPIs. Hibernate Validator is the Reference Implementation (RI) for Bean Validation, and GlassFish implements the EL JSR:


     <dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>5.1.2.Final</version>
  <scope>test</scope>
        </dependency>
        <dependency>
  <groupId>org.glassfish</groupId>
  <artifactId>javax.el</artifactId>
  <version>3.0.0</version>
  <scope>test</scope>
        </dependency>

Hibernate Validator requires Expression Language dependency. Without the javax.el dependency you will get the following error:


Caused by: javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath
  at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
 
  (ResourceBundleMessageInterpolator.java:172)
  at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
  
   (ResourceBundleMessageInterpolator.java:118)

  
 

Now you are ready to launch your Integration Test:


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;

public class ValidationTest {

  private Validator validator;

  @Before
  public void init() {

    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    this.validator = vf.getValidator();

  }

  @Test
  public void prereqsMet() {
    Workshop validWorkshop = new Workshop(2, 2, true, 3);
    Set<ConstraintViolation<Workshop>> violations = this.validator.validate(validWorkshop);
    assertTrue(violations.isEmpty());
  }  
}

Strictly speaking it is not a unit test, rather an Integration Test. In Unit Test you would like to test the validator logic only, without any dependencies to the SPI.

See you at Java EE Workshops at MUC Airport , especially at the Java EE 7 / Java 8 Testing day!

Posted at11:37AM Sep 15, 2014byAdam Bienin Real World Java EE Patterns - Rethinking Best Practices | Comments[0]| Views/Hits: 0

Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and  Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值