加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Bean验证:如何手动创建ConstraintViolation?

发布时间:2020-12-15 04:19:17 所属栏目:Java 来源:网络整理
导读:我有一个特定的场景,我只能在流程的后期手动检查违规情况. 我想要做的是抛出一个ConstraintViolationException,并为它提供一个“真正的”ConstraintViolation对象(当我在堆栈中捕获异常时,我使用#{validatedValue}和violation.getPropertyPath()参数). 如何
我有一个特定的场景,我只能在流程的后期手动检查违规情况.

我想要做的是抛出一个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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读