0
0
JUnittesting~10 mins

TestRestTemplate for API testing in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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());
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes Spring Boot test context with random port-PASS
2TestRestTemplate sends GET request to '/hello' endpointHTTP request sent to local server at random port-PASS
3Server processes request and returns HTTP 200 with body 'Hello, World!'Response received by TestRestTemplate-PASS
4Test asserts that response status code is 200Response status code is 200assertEquals(200, response.getStatusCodeValue())PASS
5Test asserts that response body equals 'Hello, World!'Response body is 'Hello, World!'assertEquals("Hello, World!", response.getBody())PASS
6Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The '/hello' endpoint returns a status other than 200 or a different response body
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the API response?
AThe response status is 200 and body is 'Hello, World!'
BThe response status is 500 and body is empty
CThe response contains JSON data
DThe response status is 404
Key Result
Always verify both the HTTP status code and the response body content to ensure the API behaves as expected.