Skip to content
Advertisement

How to raise a ConstraintValidationException in a test case for bean properties with validation annotations?

I’m trying to test that my beans have correct validation annotations. I’m using spring-boot. Here is an example test case:

JavaScript

I expect the call to checkIfvalidated() and to setSomeProperty(null) to raise a ConstraintViolationException, and the tests to pass, but they both fail with:

JavaScript

My pom.xml:

JavaScript

Why is there no ConstraintViolationException raised here? The bean property has a @NotNull annotation, the bean itself is @Validated and the method signature requires a @Valid bean.

Is there a simple way to have that exception raised in the context of my test class?

When I use validation annotations on method signatures for a service interface, everything works as expected. I don’t understand where is the difference.

Service interface:

JavaScript

Service implementation:

JavaScript

Test case:

JavaScript

==> The test passes.


Working code according to the given answer:

The test class:

JavaScript

The tested bean:

JavaScript

The service interface:

JavaScript

The service implementation:

JavaScript

Advertisement

Answer

Why is there no ConstraintViolationException raised here? The bean property has a @NotNull annotation, the bean itself is @Validated and the method signature requires a @Valid bean.

Annotations by themselves do not mean anything, they should be processed in some way. In this case the @Validated annotation is processed by Spring for its beans. The test is not a Spring bean, so the framework does not look at the annotations related to valdidation, hence no exception.

Even if the test were a Spring Bean, the approach may not work out of the box. See this question for details.

Is there a simple way to have that exception raised in the context of my test class?

Take a look at this question

When I use validation annotations on method signatures for a service interface, everything works as expected. I don’t understand where is the difference.

This happens because the service is a Spring bean, but test is not. When a method on the service is invoked, it gets intercepted by MethodValidationInterceptor, which is not the case for test

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement