# Spring Boot Test ## Dependency - build.gradle ``` dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' } } ``` - pom.xml ```xml org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine ``` ## Test Code - `@SpringBootTest` ## Run Test - `./mvnw test` or `./gradlew test` ## Smoke Test ```java @SpringBootTest public class SmokeTest { @Autowired private HomeController controller; @Test public void contextLoads() throws Exception { assertThat(controller).isNotNull(); } } ``` ## Http Request Test ```java @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class HttpRequestTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void greetingShouldReturnDefaultMessage() throws Exception { assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/", String.class)).contains("Hello, World"); } } ``` ## Web MVC Test ```java @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class HttpRequestTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void greetingShouldReturnDefaultMessage() throws Exception { assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/", String.class)).contains("Hello, World"); } } ``` ## ref - https://spring.io/guides/gs/testing-web/