java – Bean验证:如何手动创建ConstraintViolation?
作者:互联网
我有一个特定的场景,我只能在流程的后期手动检查违规情况.
我想要做的是抛出一个ConstraintViolationException,并为它提供一个“真正的”ConstraintViolation对象(当我在堆栈中捕获异常时,我使用#{validatedValue}和violation.getPropertyPath()参数).
如何在没有框架通过注释(我使用Hibernate Validator)为我做这个的情况下自己创建ConstraintViolation?
代码示例:
List<String> columnsListForSorting = new ArrayList<String>(service.getColumnsList(domain));
Collections.sort(columnsListForSorting);
String firstFieldToSortBy = this.getTranslatedFieldName(domain.getClass().getCanonicalName(), sortingInfo.getSortedColumn());
if (!columnsListForSorting.contains(firstFieldToSortBy)){
throw new ConstraintViolationException(<what here?...>);
}
谢谢.
解决方法:
在我看来,最简单的方法是模拟你的服务在你的测试中抛出约束违规.例如,您可以通过扩展类来手动完成,或者您可以使用模拟框架,例如mockito.我更喜欢模拟框架,因为它们简化了很多事情,因为您既不必创建和维护其他类也不必处理注入它们在您的测试对象中.
以mockito为起点,你可能会写一些类似于:
import org.hibernate.exception.ConstraintViolationException;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
public class MyTest {
@Mock /* service mock */
private MyService myService;
@InjectMocks /* inject the mocks in the object under test */
private ServiceCaller serviceCaller;
@Test
public void shouldHandleConstraintViolation() {
// make the mock throw the exception when called
when(myService.someMethod(...)).thenThrow(new ConstraintViolationException(...))
// get the operation result
MyResult result = serviceCaller.doSomeStuffWhichInvokesTheServiceMethodThrowingConstraintViolation();
// verify all went according to plan
assertWhatever(result);
}
}
标签:hibernate-validator,java,validation,bean-validation 来源: https://codeday.me/bug/20190728/1562937.html