我想测试follow方法
@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
它是我的测试类:
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();
}
请记住,当您模拟一个类时,所有方法调用都会变成 stub :它们是伪造的方法调用,本质上不执行任何操作,而是返回您指定的任何内容。
因此,当调用 sortingService.checkForFullLoading()
时,它实际上什么都不做,因为 sortingService
是一个模拟对象。这意味着 sortingService.startForNewSort()
因此永远不会被调用,并且验证正确地识别了这一点。
您需要以 sortingService 不被模拟的方式执行测试,以便当调用 checkForFullLoading()
时,它会被真正执行。如果 startForNewSort()
仅在该类中使用,则应将其设置为私有(private)(如果执行此操作,则在测试中将看不到它,因此如果您想验证它是否被调用,您需要使用与其交互的模拟以确保它被调用并起作用)。如果在 SortingService
之外调用 startForNewSort()
,您最终可能不得不监视 SortingService
而不是进行模拟。
关于java - Mockito框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32072981/