java - How to mock property set in constructor -


let's have class following constructor:

public class myimpl extends abstract<foo> {      @autowired     private fooclass foo;      private final threadpoolexecutor executor;      public myimpl(string name, int num) {         super(name);         this.executor = (threadpoolexecutor) executors.newfixedthreadpool(num);      } 

somewhere class has following method:

    @override     public void dothis() {         (int = 0; < num; i++) {             executor.execute(() -> foo.domethod());         }         executor.shutdown();          super.dothis();     } 

now, want test foo.domethod has been called 4 times and executor.execute(any()) , executor.shutdown() have been called 4 times well.

so far have

@runwith(powermockrunner.class) @preparefortest(executors.class) public class myimpltest {      private static final int num = 4;      @mock     private fooclass foo;     @mock     private threadpoolexecutor executor;     @injectmocks     private myimpl imyimpl = new myimpl("name", num);      @test     public void shouldcallfourtimes() throws exception {         powermockito.mockstatic(executors.class);         when(executors.newfixedthreadpool(num)).thenreturn(foo);          myimpl.dothis();          powermockito.verifystatic();         executors.newfixedthreadpool(num);         verify(foo, times(num)).domethod());      } 

however not working. mockito says there haven't been interaction mock executors. since @autowired dependencies not part of constructor, need specify constructor in field @injectmocks. however, time powermockito.mockstatic(executors.class), constructor of myimpl has created own executor through "real" executors.newfixedthreadpool.

any idea how can solve this?

update: apparently it's not big deal change design , have following:

public class myimpl extends abstract<foo> {      @autowired     private fooclass foo;      private final threadpoolexecutor executor;      public myimpl(string name, threadpoolexecutor executor) {         super(name);         this.executor = executor; } 

test:

@mock private threadpoolexecutor executor; @injectmocks private myimpl imyimpl = new myimpl("name", executor); 

however, executor somehow null when arriving constructor.

the problem design of myimpl.

instead of creating thread pool executor in constructor, should passed it. can put static factory method current contructor in place still have ability create instance same arguments using now.

why need cast threadpoolexecutor? lets depend on specific implementation. if don't need this, better of java.util.concurrent.executorservice.

then have in place use plain mockito ordinary executorservice mock.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -