java - Mockito Error when initializing instance variables from within a contructor -


i writing unit tests spring application using mockito , following unit test service class.

service class:

@service class myserviceimpl implements myservice{     @autowired     private externalservice externalservice;      myserviceimpl () {         int value = externalservice.getvalues();     }   } 

as can notice initialize instance variable inside constructor using method service class called externalservice autowired.

test class:

public class lotteryserviceimpltest {     @injectmocks     private myserviceimpl myservice;      @mock     private externalservice externalservice;      @before     public void init() {         mockitoannotations.initmocks(this);     }      @test     public void testgetlotteryresult() {         //test specific code     } } 

when run test gives error:

org.mockito.exceptions.base.mockitoexception:      cannot instantiate @injectmocks field named 'value' of type 'myserviceimpl'.     haven't provided instance @ field declaration tried construct instance.     constructor or initialization block threw exception : null 

how can create mock service before injecting test object when constructor of test object depends on mock?

the problem in way injecting , using externalservice dependency in myserviceimpl class. @autowired processed beanpostprocessor () runs after bean has been instantiated.hence value of externalservice reference initialized after constructor has run. cant use in constructor because @ point still null;

you can fix moving line int value = externalservice.getvalues(); constructor business method.

if want initialize value once @ startup can make use of @postconstruct initialization callback so

@service class myserviceimpl implements myservice{     @autowired     private externalservice externalservice;     private int value;      myserviceimpl () {      }      @postconstruct      public void initvalue(){         value = externalservice.getvalues();      } } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -