【发布时间】:2021-05-24 13:52:20
【问题描述】:
代码说明: MainThread 根据用户列表创建 ChildThread - 每个用户一个 ChildThread。我正在尝试为 MainThread 编写一个单元测试用例,并且我想跳过 ChildThread 的实现(将为 ChildThread 编写一个单独的单元测试用例)。下面是代码sn-p。
@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 实现这一点?
任何帮助将不胜感激。
【问题讨论】:
-
问题出在
usersDTOs.stream().map(ChildThread::new).forEach(executor::execute)因为它创建的是真实对象而不是模拟。您应该将ChildThread创建替换为其他服务或以某种可以模拟的方法创建 -
这行得通。谢谢@Alex
标签: java multithreading junit java-8 mockito