利用Spring Boot配置的TestNG测试用例详解

与JUnit不同,Spring Boot本身没有提供与TestNG集成的基础设施。

那么如何利用Spring Boot的配置,执行一个TestNG测试用例呢?在Spring Boot提供的大量samples中,有一个spring-boot-sample-testng可供参考。

基于该sample中,我们的TestNG测试类如下:

@SpringBootTest(classes = { ClientLauncher.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestHealthCheckTestNGClient extends AbstractTestNGSpringContextTests {
    
    @Autowired
    private HealthCheckClient healthCheckClient;
    
    @Test
    public void getHealthCheckIntegrationTest(){
        ResponseEntity> healthCheckResponse = healthCheckClient.getHealthCheck();
        assert HttpStatus.OK.equals(healthCheckResponse.getStatusCode());
    }
}

注意,测试类继承了spring-test专为TestNG实现的AbstractTestNGSpringContextTests类。

对比JUnit测试用例,由于spring-test模块提供了专门的集成JUnit的SpringRunner,测试用例的写法就与JUnit测试用例的写法非常类似了,代码示例如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { ClientLauncher.class }, webEnvironment = WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestHealthCheckClient {
    
    @Autowired
    private HealthCheckClient healthCheckClient;
    
    @Test
    public void getHealthCheckIntegrationTest() throws Exception{
        ResponseEntity> healthCheckResponse = healthCheckClient.getHealthCheck();
        Assert.assertEquals(HttpStatus.OK, healthCheckResponse.getStatusCode());
    }
}


参考链接:

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-testng

你可能感兴趣的:(TestNG,Spring,framework,Test)