\u0022package com.lenovo.tcs.automationreleasedashboard.schedule;\n\nimport com.lenovo.tcs.automationreleasedashboard.entity.RequestEntity;\nimport com.lenovo.tcs.automationreleasedashboard.mapper.RequestMapper;\nimport com.lenovo.tcs.automationreleasedashboard.service.ParentState;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.scheduling.annotation.Scheduled;\nimport org.springframework.stereotype.Component;\nimport org.springframework.util.CollectionUtils;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n@Slf4j\n@Component\npublic class StateMachineScheduler {\n private List stateList;\n \n @Autowired\n RequestMapper requestMapper;\n\n public StateMachineScheduler() {\n stateList = new ArrayList<>();\n }\n\n public StateMachineScheduler(List states) {\n stateList = states;\n }\n\n @Scheduled(cron = "${schedule.timer}")\n public void stateControl() {\n System.out.println("Schedule task starting...");\n if (CollectionUtils.isEmpty(stateList)) {\n System.out.println("There is no state in list.");\n return;\n }\n\n List waitingList = requestMapper.getRequestByStateList(stateList.stream().map(state -> state.getStateEnum().getCode()).collect(Collectors.toList()));\n\n for (RequestEntity requestEntity : waitingList) {\n for (ParentState state : stateList) {\n if (state.getStateEnum().getCode() == requestEntity.getCurrentReleaseState()) {\n state.execute(requestEntity);\n break;\n }\n }\n }\n\n System.out.println("Schedule task ends.");\n }\n}\n\u0022对以上代码进行单元测试,可以使用以下步骤:\n\n1. 创建一个测试类,并使用@RunWith(MockitoJUnitRunner.class)注解标记该类,以便使用Mockito进行测试。\n\n2. 在测试类中创建一个StateMachineScheduler对象作为待测试对象,并使用@InjectMocks注解进行注入。\n\n3. 使用@Mock注解创建一个RequestMapper的模拟对象。\n\n4. 在测试方法中使用Mockito.when()方法来设置当调用模拟对象的方法时,返回的预期结果。\n\n5. 调用待测试对象的方法进行测试。\n\n以下是一个示例测试类的代码:\n\njava\n@RunWith(MockitoJUnitRunner.class)\npublic class StateMachineSchedulerTest {\n\n @InjectMocks\n private StateMachineScheduler stateMachineScheduler;\n\n @Mock\n private RequestMapper requestMapper;\n\n @Test\n public void testStateControl() {\n // 设置模拟对象的方法调用返回的预期结果\n List<RequestEntity> waitingList = new ArrayList<>();\n Mockito.when(requestMapper.getRequestByStateList(Mockito.anyList())).thenReturn(waitingList);\n\n // 调用待测试对象的方法\n stateMachineScheduler.stateControl();\n\n // 验证预期结果是否符合预期\n // 可以使用Mockito.verify()方法来验证模拟对象的方法是否被调用,\n // 或者使用Mockito.verifyNoMoreInteractions()方法来验证模拟对象的方法是否只被调用了一次\n }\n}\n\n\n在测试方法中,可以使用Mockito.verify()方法来验证模拟对象的方法是否被调用,并可以使用Mockito.verifyNoMoreInteractions()方法来验证模拟对象的方法是否只被调用了一次。你还可以根据需要添加更多的测试方法来覆盖不同的情况和边界条件。\n


原文地址: https://www.cveoy.top/t/topic/pL66 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录