К основному контенту

Сообщения

Показаны сообщения с ярлыком "Validation"

Use @SpringBootTest for validator's unit test and be fast enough

This a continuation of the post: https://live-scripts.blogspot.com/2020/02/unit-testing-object-validation-with-di-in-validator.html#more . Last time we talked about testing a validator, which has a dependency. Using pure @SpringBootTest turned out to be too slow. So I showed a "trick" to override the validator's factory in order to inject the dependant object. This reduced test run time. I promised to show a way to use @SpringBootTest , autowiring, and still be quick enough.

Unit-testing object validation when validator has DI

Summary Unit test object validation when validator(s) has a dependency. For instance, we have some custom field and cross-field validators. Want to test their combination. Additionally some of validators have dependencies, injected through constructor or setters. You're not using property injection, right? Shortcut If you are just searching for an answer, here's the fast way: Declare CustomConstraintValidatorFactory that implements javax.validation.ConstraintValidatorFactory Override getInstance method and on facing your constraint validator class instantiate it Otherwise delegate validator construction to org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl Build validator factory and provide it your CustomConstraintValidatorFactory Build validator, using that factory... Go to demo project on GitHub for details:  https://github.com/MrArtemAA/blog-demos/blob/master/test-validator-with-injection/src/test/java/ru/artemaa/...