java - Mockito and CDI bean injection, does @InjectMocks call @PostConstruct? -


i have code:

class patient {    @inject syringe syringe;    @postconstruct   void saythankyoudoc() {      system.out.println("that hurt crazy!");    }  }  @runwith(mockitojunitrunner.class) class testcase {    @mock   syringe siringemock;    @injectmocks   patient patient;    //...  } 

i expected mockito call postconstruct, had add:

@before public void simulate_post_construct() throws exception {     method postconstruct = patient.class.getdeclaredmethod("saythankyoudoc", null);     postconstruct.setaccessible(true);     postconstruct.invoke(patient); } 

is there better way this?

although not direct answer question, suggest move away field injection , use constructor injection instead (makes code more readable , testable).

your code like:

class patient {    private final syringe syringe;    @inject   public patient(syringe syringe) {     system.out.println("that hurt crazy!");   }  } 

then test be:

@runwith(mockitojunitrunner.class) class testcase {    @mock   syringe siringemock;    patient patient;    @before   public void setup() {      patient = new patient(siringemock);   }  } 

update

as suggested erik-karl in comments, use @injectmocks rid of setup method. solution works because mockito use appropriate constructor injection (as described here). code like:

@runwith(mockitojunitrunner.class) class testcase {    @mock   syringe siringemock;    @injectmocks   patient patient;  } 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -