Unit test a spring component with private constructor without injection

EnzoMolion :

I have a @Component-annotated class, injected using a private constructor, and @Autowired-annotated setters for nested injection.

In order to unit test it, a workaround I found is to use @SpringBootTest and @DirtiesContext annotations in order to create Spring context with injected component to test and "re-wire" it after each test.

However, I want to unit test this component without its context (in order to avoid having to build all context before every test).

I can without any problem mock every nested injection (as I want to test the controller only here).

Hence my question : how can I "get" this component's instance ? How can I reset it before each test ? How should I then get my mocked nested injections (that I will - I guess - "inject" via my setters) ?

Christian Frommeyer :

Don't use a private constructor. There is no benefit from having a private constructor and then using reflection to still only call it from the outside. You should only use a private constructor if the class has only static member to make it clearer that the class is not meant to be instantiated or if you are using a static factory method in the same class to create instances.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328718&siteId=1