Disabling @Valid Annotation in a Spring Integration Test

Featured image for sharing metadata for article

Today I was writing some Spring integration tests to validate some new endpoints had a Filter applied correctly, but I was fighting with the endpoint methods requiring the request to be valid.

This was because the request body was annotated with @Valid (but is true for other JSR380 annotations) which Spring Boot then adds validation for - Validation in Spring Boot on Baeldung has some good information about it.

I didn't really want each request I was sending to require full validation, as the requests required a lot of setup, and that wasn't really what I was trying to test at this point.

Thanks to my colleague James, I now have a way around that!

Spring Boot 2.x.x uses a LocalValidatorFactoryBean to orchestrate the validation of these, which means if you provide the following MockBean, you can remove its validation:

@MockBean private LocalValidatorFactoryBean validator;

Leaving it without any test setup will disable any validation that may be performed for @Valid annotations as there is no implementation behind it to perform validation. But if you want to do anything extra, you can set it up as needed.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #spring #spring-boot #jsr380 #bean-validation.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.