dimanche 29 juillet 2018

How can I inject property source of a bean in test

I am writing unit tests for my services in Spring, Java. I mock all dependencies in a tested class and I instantiate the tested class in a constructor, to which I pass mocked classes. The problem is that the tested class injects properties from .properties file into fields that are inside it (let's say Strings).

I use the standard combination of @PropertySource on a class level and @Value on a field level inside my tested class.

As we know, properties injection fails when class is instantiated through constructor (not as a bean during the Spring Container initialization). How do you deal with such problem?

I've got one solution, though I think it is bad and unsatisfactory, that is: 1. to @Autowire the class under test normally, then replace all its dependencies by using a setter.

I also know about the @TestPropertySource annotation and if I understand correctly, it does not provide a solution and it is only a way to override already existent properties - which is not the case, as we cannot really use any properties.

Thanks for help in advance :)

Aucun commentaire:

Enregistrer un commentaire