0
0
JUnittesting~5 mins

TestRestTemplate for API testing in JUnit

Choose your learning style9 modes available
Introduction

TestRestTemplate helps you test APIs by sending real HTTP requests and checking responses easily.

When you want to check if your REST API returns the right data.
When you need to test API endpoints during development.
When you want to verify HTTP status codes and response bodies.
When you want to simulate client requests to your server in tests.
Syntax
JUnit
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/api/example", String.class);

Use getForEntity to send a GET request and get full response details.

TestRestTemplate is easy to use for integration tests in Spring Boot.

Examples
Simple GET request test checking status and response body.
JUnit
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/api/hello", String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("Hello World", response.getBody());
POST request test sending JSON data and checking creation status.
JUnit
TestRestTemplate restTemplate = new TestRestTemplate();
Map<String, String> request = Map.of("name", "Alice");
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/api/greet", request, String.class);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
Sample Program

This test sends a GET request to /api/hello and checks if the response is 200 OK with body "Hello World".

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.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ApiTest {

    private final TestRestTemplate restTemplate = new TestRestTemplate();

    @Test
    public void testGetHello() {
        ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/api/hello", String.class);
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertEquals("Hello World", response.getBody());
    }
}
OutputSuccess
Important Notes

Make sure your API server is running on the expected port before running tests.

Use SpringBootTest.WebEnvironment.DEFINED_PORT to test with a real server port.

TestRestTemplate is good for integration tests, not unit tests.

Summary

TestRestTemplate sends real HTTP requests to test APIs.

It helps check status codes and response content easily.

Use it in integration tests to simulate client calls.