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 |
TestRestTemplate in JUnit testing?TestRestTemplate in a Spring Boot test class?@Autowired is used to inject TestRestTemplate automatically.@InjectMocks is incorrect for TestRestTemplate injection in Spring Boot tests.TestRestTemplate:
ResponseEntity<String> response = restTemplate.getForEntity("/api/users/1", String.class);
int statusCode = response.getStatusCodeValue();
String body = response.getBody();
If the API returns HTTP 200 with body "User Found", what will be the values of statusCode and body?TestRestTemplate:
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGetUser() {
ResponseEntity<String> response = restTemplate.getForEntity("/api/users/", String.class);
assertEquals(200, response.getStatusCodeValue());
}
What is the likely problem with this test?/api/users that creates a user and returns HTTP 201 with the created user JSON. Which TestRestTemplate method and assertion combination correctly tests this?postForEntity is appropriate for sending the user object.Pass the test and this pattern moves unknown