ExecutorService 를 사용하여 별도의 스레드로 실행시키는 메소드를 테스트 할 경우
다른 스레드로 실행되므로 테스트 시 정상적인 리턴값을 받아오지 못하는 문제가 발생함.
Solving
replace ExecutorService field to MoreExecutors.newDirectExecutorService()
if the filed is declared Bean then use @Mock annotation.
but it just declared normal field, you must use ReflectionTestUtils of Spring Framework
// Test Target
public class YourService {
private static ExecutorService executor = Executors.newFixedThreadPool(5);
public void start(List<YourVO> vos) {
vos.forEach(vo -> executor.execute(() ->
{ ..... } // do something
)
);
}
// Test Code
import com.google.common.util.concurrent.MoreExecutors;
import org.springframework.test.util.ReflectionTestUtils;
// if static field
ReflectionTestUtils.setField(YourService.class,"executor", MoreExecutors.newDirectExecutorService());
// if not static field
ReflectionTestUtils.setField(yourServiceInstance.class,"executor", MoreExecutors.newDirectExecutorService());
Problem
ExecutorService 를 사용하여 별도의 스레드로 실행시키는 메소드를 테스트 할 경우 다른 스레드로 실행되므로 테스트 시 정상적인 리턴값을 받아오지 못하는 문제가 발생함.
Solving
replace ExecutorService field to MoreExecutors.newDirectExecutorService()
if the filed is declared Bean then use @Mock annotation. but it just declared normal field, you must use ReflectionTestUtils of Spring Framework