簡體   English   中英

如何使用 mockito-inline 模擬子線程的 run() 方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM