<!-- Mockito extention-->
<dependency>
<groupId>prg.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<!-- for mock static-->
<dependency>
<groupId>prg.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
public static XxxEventApplication {
private static final Logger LOGGER = LoggerFactory.getLogger("XxxEventApplication .class");
public static void main (String[] args){
SpringApplication.run(XxxEventApplication .class, args);
LOGGER.info("Succeed to start Csap Event Service...");
}
}
@ExtendWith(MockitoExtension.class)
class XxxEventApplication Test {
@Test
void main() {
try(MockedStatic<SpringApplication> mockStatic = Mockito.mockStatic(SpringApplication.class)){
String[] args = new String[]{"1"};
mockStatic.when(() -> SpringApplication.run(CsapEventApplication.class, args))
.then(invocation -> null);
CsapEventApplicatio.main(args);
mockStatic.verify(() -> SpringApplication.run(CsapEventApplication.class, args));
}
}
}
其实和controller /service 层单元测试逻辑本质是一样的,现在只不过是为了测试main函数,那么需要mock 被测试的main函数中的其他函数,然后调用main函数,验证被mock的函数是否被调用。
@ExtendWith(MockitoExtension.class)
class EventControllerTest {
@Mock
private IEventService eventService;
@Mock
private EventController eventController;
@Test
void removeTest() {
Long[] deleteIds = {20230306L};
Mockito.when(eventService.deleteEventByIds(Mockito.any(Long[].class)))
.thenReturn(1);
AjaxResult actualResult = eventController.remove(deleteIds);
AjaxResult expectedResult = AjaxResult.success();
Assertions.assertEquals(expectedResult, actualResult);
}
}