java / intermediate
Snippet
Unit Testing Outbound API Clients with MockRestServiceServer
@RestClientTest focuses testing solely on RestTemplate or RestClient builders by mocking external HTTP endpoints via MockRestServiceServer. It asserts correct URL construction, header propagation, and payload deserialization without opening real network sockets.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestClientTest(GithubClient.class)class GithubClientTest {@Autowiredprivate GithubClient githubClient;@Autowiredprivate MockRestServiceServer server;@Testvoid fetchesUserRepositories() {this.server.expect(requestTo("/users/octocat/repos")).andRespond(withSuccess("[{\"name\":\"repo1\"}]", MediaType.APPLICATION_JSON));List<RepositoryDto> repos = githubClient.getRepositories("octocat");assertThat(repos).hasSize(1);}}
spring
Breakdown
1
@RestClientTest(GithubClient.class)
Prepares an isolated test slice specifically for the specified REST client bean.
2
this.server.expect(requestTo("/users/octocat/repos"))
Declares expectations for the outbound HTTP request URI.
3
.andRespond(withSuccess(...))
Mocks an HTTP 200 response with custom payload and media type headers.