[英]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.代码说明: MainThread 根据用户列表创建 ChildThread - 每个用户一个 ChildThread。 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).
我正在尝试为 MainThread 编写一个单元测试用例,并且我想跳过 ChildThread 的实现(将为 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.尽管监视了 ChildThread,但仍执行 ChildThread 的 run() 方法。 doNothing().when(spy).run();
doNothing().when(spy).run(); is of no effect.
没有效果。 For some reason, I cannot use PowerMockito.
出于某种原因,我不能使用 PowerMockito。 How to achieve this with mockito-inline (version 3.10.0) and java8?
如何使用 mockito-inline(版本 3.10.0)和 java8 实现这一点?
Any help would be appreciated.任何帮助,将不胜感激。
Instead of mocking ChildThread refactor MainThread so ExecutorService is injected in constructor.而不是 mocking ChildThread 重构 MainThread 所以 ExecutorService 被注入构造函数。
Then mock ExecutorService and check if it is receiving correct ChildThread instances.然后模拟 ExecutorService 并检查它是否接收到正确的 ChildThread 实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.