M06H
M06H

Reputation: 1783

mocking Executorservice field in unit test

I have this service class that I am trying to Unit test using mockito but is failing:

@Service("processor")
public class AsyncProcessor extends Processor {

    @Value("${queue.size}")
    private int queueSize;

    @Value("${executor.corePoolSize}")
    private int corePoolSze;

    @Value("${executor.maxPoolSize}")
    private int maxPoolSize;

    @Value("${executor.keepAliveTime}")
    private int keepAliveTime;

    private final JobRunner jobRunner;

    private final ExecutorService executorService;

    public AsyncProcessor(final MyRepo repo,
                              final JobRunner jobRunner) {
        super(repo);
        this.jobRunner = jobRunner;
        executorService = new ThreadPoolExecutor(corePoolSze, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
                                                 new LinkedBlockingQueue<>(queueSize));
    }
    ///

}

So I have written this test class:

@ExtendWith(MockitoExtension.class)
public class AsyncProcessorTest{

    @Mock
    private MyRepo repo;

    @Mock
    private JobRunner jobRunner;


    @InjectMocks
    private AsyncProcessor asyncProcessor;


    @Test
    public void someTest() {
    }

}

When I run my tests, i get error with inject mocks.

The error appears when it tried to instantiate the executorService on the constructor.

My question is how can I mock it and use it and overcome this error?

Upvotes: 1

Views: 2405

Answers (1)

Nir Levy
Nir Levy

Reputation: 12953

I would initialize the service a bit differently - instead of having the protperties in this class and creating the executorService in the c'tor - make it a separate bean and inject it.

in your application context:

@Value("${queue.size}")
private int queueSize;

@Value("${executor.corePoolSize}")
private int corePoolSze;

@Value("${executor.maxPoolSize}")
private int maxPoolSize;

@Value("${executor.keepAliveTime}")
private int keepAliveTime;

@Bean
ExecutorService executorService() {
  return new ThreadPoolExecutor(corePoolSze, maxPoolSize, keepAliveTime, 
        TimeUnit.SECONDS,new LinkedBlockingQueue<>(queueSize));
}

And then inject it in the c'tor of your service.
This will allow you to provide a mock in your unit test

Upvotes: 1

Related Questions