简体   繁体   中英

How to mock run() method of child thread using mockito-inline

Code explanation: MainThread creates ChildThread based on the list of users - one Childthread per user. I am trying to write a unit test case for MainThread and I want to skip the implementation of ChildThread (a separate unit test case will be written for ChildThread). Below is the code snippet.

@Slf4j
public class MainThread implements Runnable {
 private static final UserService USER_SERVICE = ApplicationContextUtils.getApplicationContext().getBean("userService", UserService.class);
 private final String threadName;

 public MainThread(String threadName) {
    this.threadName = threadName;
 }

 public void run() {
    log.info("{} thread created at {}", threadName, LocalDateTime.now());
    List<UsersDTO> usersDTOs = USER_SERVICE.getUsers();
    ExecutorService executor = Executors.newFixedThreadPool(usersDTOs.size());
    usersDTOs.stream().map(ChildThread::new).forEach(executor::execute);
    executor.shutdown();
 }
}

@Slf4j
 public class ChildThread implements Runnable {
 private final UserDTO userDTO;

 public ChildThread(UserDTO userDTO) {
    this.userDTO = userDTO;
 }

 public void run() {
    log.info("Child thread created for user: {}", userDTO.getName());
    // some business logic
 }
}

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MainThreadTest {

 @Mock
 private ApplicationContext applicationContext;
 @Mock
 private UserService userService;

 @BeforeEach
 public void setUp() {
    MockitoAnnotations.openMocks(this);
    new ApplicationContextUtils().setApplicationContext(applicationContext);
 }

 @Test
 void test() {
    Mockito.when(applicationContext.getBean("userService", UserService.class)).thenReturn(userService);
    Mockito.when(userService.getUsers()).thenReturn(MockObjectHelper.getUsersList());

    ChildThread childThread = new ChildThread(MockObjectHelper.getUser());
    ChildThread spy = spy(childThread);
    doNothing().when(spy).run();

    MainThread mainThread = new MainThread("TestingThread");
    mainThread.run();

    verify(userService, times(1)).getUsers(any());
 }
}

Despite spying ChildThread, the run() method of ChildThread is executed. doNothing().when(spy).run(); is of no effect. For some reason, I cannot use PowerMockito. How to achieve this with mockito-inline (version 3.10.0) and java8?

Any help would be appreciated.

Instead of mocking ChildThread refactor MainThread so ExecutorService is injected in constructor.

Then mock ExecutorService and check if it is receiving correct ChildThread instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM