Mockito框架

Mockito framework

我想测试跟随方法

@Service
public class SortingService {

    @Autowired
    private SortingExecutionCore sortingExecutionCore;

    @Autowired
    private TaskService taskService;

public void checkForFullLoading() {
    Integer countOfThreads = sortingExecutionCore.countOfFreeThreads();
    Integer countOfWaitingTasks = taskService.waitingTaskCount();
    for (int i = 0; i < countOfSearchsForWaitingTask; i++) {
            try {
                startForNewSort();
...

startForNewSort - SortingService 方法 SortingExecutionCore 和 TaskService - spring beans

这是我的测试class:

 public class SortingServiceTest {

        @InjectMocks
        SortingService sortingService;

        @Mock
        SortingExecutionCore sortingExecutionCore;

        @Mock
        TaskService taskService;

        @Before
        public void initMocks(){
            sortingService = mock(SortingService.class);
            MockitoAnnotations.initMocks(this);
        }

        @Test
        public void testCheckForFullLoading() throws Exception {

            when(sortingExecutionCore.countOfFreeThreads()).thenReturn(1);
            when(taskService.waitingTaskCount()).thenReturn(1);

            sortingService.checkForFullLoading();
            verify(sortingService, times(1)).startForNewSort();

        }

而当我运行测试时。我已经有了 需要但未调用的异常

问题是您嘲笑了您正在尝试测试的 class。让我们检查一下您的测试方法:

@Test
    public void testCheckForFullLoading() throws Exception {

        when(sortingExecutionCore.countOfFreeThreads()).thenReturn(1);
        when(taskService.waitingTaskCount()).thenReturn(1);

        sortingService.checkForFullLoading();  //Stubbed method on mocked class.
        verify(sortingService, times(1)).startForNewSort();

    }

请记住,当您模拟一个 class 时,所有方法调用都会变成存根:它们是伪造的方法调用,本质上什么都不做,而不是返回您指定的任何内容。

所以,当 sortingService.checkForFullLoading() 被调用时,它实际上什么都不做,因为 sortingService 是一个模拟对象。这意味着 sortingService.startForNewSort() 因此永远不会被调用,并且验证正确地识别了这一点。

您需要以不模拟 sortingService 的方式执行测试,以便在调用 checkForFullLoading() 时真正执行。如果 startForNewSort() 仅在 class 中使用,则应将其设为私有(如果您这样做,它在测试中是不可见的,因此如果您想验证它是否被调用,则需要使用与它交互的对象的模拟来确保它被调用和运行)。如果 startForNewSort()SortingService 之外调用,您可能最终不得不监视 SortingService 而不是模拟。