我想测试追踪方法

@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 bean

它是我的测试班:

 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();

        }


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

最佳答案

问题是您嘲笑了您要测试的类。让我们检查一下您的测试方法:

@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();

    }


请记住,当模拟一个类时,所有方法调用都将成为存根:它们被伪装为本质上不执行任何操作的方法调用,而是返回您指定的内容。

因此,当sortingService.checkForFullLoading()被调用时,它实际上不执行任何操作,因为sortingService是一个模拟对象。这就是说,因此永远不会调用sortingService.startForNewSort(),并且验证会正确地识别出它。

您需要以不模拟sortingService的方式执行测试,以便在调用checkForFullLoading()时将其真实执行。如果startForNewSort()仅在该类中使用,则应将其设为私有(如果执行此操作,它将在测试中不可见,因此,如果要验证它是否被调用,则需要使用其交互内容的模拟方法,以确保它被调用并起作用)。如果在startForNewSort()之外调用SortingService,则可能最终不得不监视SortingService而不是嘲笑。

关于java - Mockito框架,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32072981/

10-12 04:08