Test Overview
This test uses TestRestTemplate to call a REST API endpoint and verifies that the response status is 200 OK and the response body contains the expected message.
This test uses TestRestTemplate to call a REST API endpoint and verifies that the response status is 200 OK and the response body contains the expected message.
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ApiTest { @Autowired private TestRestTemplate restTemplate; @Test public void testHelloEndpoint() { ResponseEntity<String> response = restTemplate.getForEntity("/hello", String.class); assertEquals(200, response.getStatusCodeValue()); assertEquals("Hello, World!", response.getBody()); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes Spring Boot test context with random port | - | PASS |
| 2 | TestRestTemplate sends GET request to '/hello' endpoint | HTTP request sent to local server at random port | - | PASS |
| 3 | Server processes request and returns HTTP 200 with body 'Hello, World!' | Response received by TestRestTemplate | - | PASS |
| 4 | Test asserts that response status code is 200 | Response status code is 200 | assertEquals(200, response.getStatusCodeValue()) | PASS |
| 5 | Test asserts that response body equals 'Hello, World!' | Response body is 'Hello, World!' | assertEquals("Hello, World!", response.getBody()) | PASS |
| 6 | Test ends successfully | All assertions passed | - | PASS |