Skip to content
Advertisement

In Java, how to test a private code running in parallel with executor service wrapped in public method

I had an existing non-parallel code that we recently made concurrent by using executor service. Adding concurrency ensured limit the number of requests sent to another API in our scenario. So we are calling an external service and limiting requests, waiting for all requests to complete so as merge the responses later before sending the final response.

I am stuck on how to add a unit test/mock test to such a code, considering the private method is parallelized. I have added below my code structure to explain my situation.

I am trying to test here

@Test
public void processRequest() {
  ...
}

Code

int MAX_BULK_SUBREQUEST_SIZE = 10;
public void processRequest() {
    ...
    // call to private method
    ResponseList responseList = sendRequest(requestList);
}

private void sendRequest(List<..> requestList) {
   List<Response> responseList = new ArrayList<>();
   ExecutorService executorService = Executors.newFixedThreadPool(10);
   
   int numOfSubRequests = requestList.size();
   for (int i = 0; i < numOfSubRequests; i += MAX_BULK_SUBREQUEST_SIZE) {
                List<Request> requestChunk;
                if (i + MAX_BULK_SUBREQUEST_SIZE >= numOfSubRequests) {
                    requestChunk = requestList.subList(i, numOfSubRequests);
                } else {
                    requestChunk = requestList.subList(i, i + MAX_BULK_SUBREQUEST_SIZE);
                }
                
                // parallelization
                executorService.submit(() -> {
                    Response responseChunk = null;
                    try {
                        responseChunk = callService(requestChunk); // private method
                    } catch (XYZException e) {
                        ...
                        try {
                            throw new Exception("Internal Server Error");
                        } catch (Exception ex) {
                            ...
                        }
                    }
                    responseList.add(responseChunk);
                });
            }
            executorService.shutdown();
            try {
                executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {..}
        }
        return responseList;

}

private Response callService(..) {

  // call to public method1
  method1(..);

  // call to public method2
  method2(..);
}

Advertisement

Answer

I was able to do so with unit tests and adding a mockito verify on how many times a method is called. If it’s running in parallel after chunkifying, then the method will be called more than once equal to number of chunks it’s going to process.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement