-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuoteControllerTest.java
More file actions
73 lines (61 loc) · 2.71 KB
/
Copy pathQuoteControllerTest.java
File metadata and controls
73 lines (61 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.consumingrest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.restclient.test.autoconfigure.AutoConfigureMockRestServiceServer;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Tests for {@link QuoteController} endpoints.
* Uses MockRestServiceServer to mock the quote-service backend.
*/
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureMockRestServiceServer
class QuoteControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private MockRestServiceServer server;
@Test
void getQuote_whenBackendAvailable_returnsQuote() throws Exception {
// Given - mock the quote-service response
String quoteJson = """
{
"type": "success",
"value": {
"id": 1,
"quote": "Test quote from mock server"
}
}
""";
server.expect(requestTo("http://localhost:8080/api/random"))
.andRespond(withSuccess(quoteJson, MediaType.APPLICATION_JSON));
// When/Then - call our controller and verify response
mockMvc.perform(get("/quote"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.type", is("success")))
.andExpect(jsonPath("$.value.quote", is("Test quote from mock server")));
server.verify();
}
@Test
void getQuote_whenBackendUnavailable_returnsFallback() throws Exception {
// Given - mock server error
server.expect(requestTo("http://localhost:8080/api/random"))
.andRespond(withServerError());
// When/Then - call our controller and verify fallback response
mockMvc.perform(get("/quote"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.type", is("error")))
.andExpect(jsonPath("$.value.quote", is("Quote service unavailable")));
server.verify();
}
}