2013-12-11 69 views
0

我在做什么错?测试不起作用。bean验证spring + hibernate annotion不起作用

这是我的接口类:

@Validated 
public interface ICustomerService 
{ 
    public List<Customer> findbyStr(
    @NotEmpty(message = "{column.notvalid}") 
    @NotNull(message = "{column.notvalid}") 
    String column, 
    @NotEmpty(message = "{column.notvalid}") 
    @NotNull(message = "{value.notvalid}") 
    String value); 
} 

这是我实现类:

@Service("customerService") 
@Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class CustomerService implements ICustomerService { 

    @Autowired 
    private IStorageDao<Customer> dao; 

    @Override 
    public List<Customer> findbyStr(String column, String value) { 
     return dao.findByString(Customer.class, column, value); 
    } 

} 

这是我的单元测试类: JUnit测试不起作用。

@RunWith(SpringJUnit4ClassRunner.class) 
public class CustomerTest extends BaseIntegrationTest { 
    @Autowired 
    private ICustomerService service; 
    @Autowired 
    public static Validator validator; 

    @Test 
    public void test_A6_CustomerFindByStrNull() { 
     List<Customer> result = service.findbyStr(null, null); 

     Set<ConstraintViolation<ICustomerService>> constraintViolations = validator 
       .validate(service); 

     assertEquals(0, constraintViolations.size()); 
     assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.", 
       constraintViolations.iterator().next().getMessage()); 

     assertNotNull(result); 
     assertNotNull(result.get(1)); 
    } 
} 
+0

什么不起作用?你会得到一个'NullPointerException'吗? –

+0

它需要得到一个错误信息,这并没有发生 – Fawi

+0

对不起,我打错了我,它的 'assertEquals(1,constraintViolations.size()); \t \t的assertEquals( “死angegebene电子邮件-住址IST fehlerhaft。”, \t \t \t \t constraintViolations.iterator()的next()的getMessage());'' – Fawi

回答

1

我敢肯定你不能测试ConstraintViolations当注解上的对象的方法,因为它应该抛出一个MethodConstraintViolationException。你应该尝试这样的事:

@RunWith(SpringJUnit4ClassRunner.class) 
public class CustomerTest extends BaseIntegrationTest { 

    @Autowired 
    private ICustomerService service; 

    @Test 
    public void test_A6_CustomerFindByStrNull() { 
     try { 
      List<Customer> result = service.findbyStr(null, null); 
     } catch (MethodConstraintViolationException ex) { 
      assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.", ex.getConstraintViolations().iterator().next().getMessage()); 
     } 
     fail("Exception expected"); 
    } 
} 

您需要具备以下豆你application-context.xml文件:

<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/> 
+0

你是对的我也在互联网上找到了这个解决方案,但是我在hibernate-validator版本5.0.1中找不到'MethodConstraintViolationException'类。最终 – Fawi

+0

'MethodConstraintViolationException无法解析为类型' – Fawi

+0

看起来Hibernate 5+支持只会在Spring 4中添加。它只适用于4.x版本的休眠验证器 –