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

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.

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:



Комментарии

Популярные сообщения из этого блога

Занимательные алгоритмы. Поиск цикла в односвязном списке

И снова про тараканов, которые иногда возникают в голове. Как-то раз, засыпая, я задумался на курьезными задачками из своей сферы деятельности (Lotus Notes), которые можно было бы задать на собеседовании, плавно перешел к воспоминаниям о своих первых собеседования, когда опыта работы еще не было. Опыт самих собеседований у меня не велик а места, где задавались действительно интересные задачи (а не задачки типа: написать сортировку массива любым известным способом) вообще равны одному - это ABBYY. Как минимум одна задачка в списке на знание и понимание классических алгоритмов, описанных в книге Дональда Кнута -  Искусство программирования .

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/d

Lotus Notes FAQ. 8/9 Eclipse. Как настроить уведомления о Sametime сообщениях

Н а написание данной "инструкцию" натолкнул мой коллега. Помню, первый раз сам долго искал, как отключить постоянно выпрыгивающие уведомления о новых сообщениях в Sametime. И так, речь идет о клиентах IBM Notes 8+ версии Standart (Eclipse based). Как настроить уведомления о Sametime сообщениях?