Mockito and CDI bean injection, @InjectMocks calls @PostConstruct?

I have this code:

class Patient { @Inject Syringe syringe; @PostConstruct void sayThankyouDoc() { System.out.println("That hurt like crazy!"); } } @RunWith(MockitoJUnitRunner.class) class TestCase { @Mock Syringe siringeMock; @InjectMocks Patient patient; //... } 

I expected Mockito to call PostConstruct, but I had to add:

 @Before public void simulate_post_construct() throws Exception { Method postConstruct = Patient.class.getDeclaredMethod("sayThankyouDoc", null); postConstruct.setAccessible(true); postConstruct.invoke(patient); } 

Is there a better way to do this?

+6
source share
1 answer

Although this is not a direct answer to your question, I suggest that you give up injection in the field and use constructor injection instead (it makes the code more readable and verifiable).

Your code will look like this:

 class Patient { private final Syringe syringe; @Inject public Patient(Syringe syringe) { System.out.println("That hurt like crazy!"); } } 

Then your test will be simple:

 @RunWith(MockitoJUnitRunner.class) class TestCase { @Mock Syringe siringeMock; Patient patient; @Before public void setup() { patient = new Patient(siringeMock); } } 

Update

As suggested by Erik-Karl in the comments, you can use @InjectMocks to get rid of the installation method. The solution works because Mockito will use the appropriate constructor injection (as described here ). Then the code will look like this:

 @RunWith(MockitoJUnitRunner.class) class TestCase { @Mock Syringe siringeMock; @InjectMocks Patient patient; } 
+5
source

Source: https://habr.com/ru/post/984362/


All Articles