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.
Won't take you too long. In order to that, we'll ask Spring to load on part of the context we need. This will make a huge performance boost. Spring holds a notion of test slices, but it's not what we a going to use.
The idea here is quite close to slicing: we'll load only needed components by explicitly setting the classes attribute of the @SpringBootTest.
In order to inject javax.validation.Validator and use validator.validate(), a validation module should be auto-configured by calling org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration. Add it to classes attribute alongside with our validator bean:
@SpringBootTest(classes = { ConsistentPropertiesValidator.class, ValidationAutoConfiguration.class })
ConsistentPropertiesValidator can be autowired now. The resulting test can be viewed here: https://github.com/MrArtemAA/blog-demos/blob/master/test-validator-with-injection/src/test/java/ru/artemaa/demo/ObjectToValidateSpringTest.java
The test runtime more or less the same as writing own validator's factory:
Комментарии
Отправить комментарий