Java – bean validation: how to manually create a constraintviolation?

I have a specific scenario where I can only manually check violations later in the process

What I want to do is throw a constraintviolationexception and provide it with a "real" constraintviolation object (when I catch an exception in the stack, I use #{validatedvalue} and the violation. Getpropertypath () parameters)

How can I create a constraintviolation without the framework doing this for me through annotations (I use hibernate validator)?

Code example:

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?...>);
}

thank you.

Solution

In my opinion, the easiest way is to simulate your service and throw constraint violations in your test For example, you can do this manually by extending classes, or you can use a simulation framework, such as mockito I prefer simulation frameworks because they simplify a lot of things because you don't have to create and maintain other classes or deal with injecting them into your test objects

Starting with mockito, you might write something like:

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);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>