Spring Bootで構成されたTestNGテストの用例を詳しく説明します.


JUnitと違って、Spring Boot自体はTestNGと一体化したインフラを提供していません.
Spring Bootの構成を利用して、TestNGテストケースを実施するにはどうすればいいですか?Spring Bootが提供する大量のsamplesには、spring-boot-sample-testingが参考になります.
この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のために専門的に実現したAbstract TestNGSpring ContectTests類を継承しました.
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