2013-12-11 67 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版本的休眠驗證器 –