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