-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreetingControllerTest.java
More file actions
70 lines (59 loc) · 2.47 KB
/
Copy pathGreetingControllerTest.java
File metadata and controls
70 lines (59 loc) · 2.47 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
package com.example.restservice;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Tests for {@link GreetingController} endpoints.
*/
@WebMvcTest(GreetingController.class)
class GreetingControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void greeting_withDefaultName_returnsHelloWorld() throws Exception {
mockMvc.perform(get("/greeting"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", is("Hello, World!")))
.andExpect(jsonPath("$.id", greaterThan(0)));
}
@Test
void greeting_withCustomName_returnsHelloName() throws Exception {
mockMvc.perform(get("/greeting").param("name", "Justin"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", is("Hello, Justin!")))
.andExpect(jsonPath("$.id", greaterThan(0)));
}
@Test
void greeting_incrementsId() throws Exception {
// Get initial greeting
String response1 = mockMvc.perform(get("/greeting"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
// Get second greeting
String response2 = mockMvc.perform(get("/greeting"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
// Extract IDs and verify increment
// The IDs should be different (incrementing)
mockMvc.perform(get("/greeting"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", greaterThan(0)));
}
@Test
void greeting_withEmptyName_usesDefault() throws Exception {
// Empty string triggers default value "World"
mockMvc.perform(get("/greeting").param("name", ""))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", is("Hello, World!")));
}
@Test
void greeting_withSpecialCharacters_handlesCorrectly() throws Exception {
mockMvc.perform(get("/greeting").param("name", "O'Brien"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", is("Hello, O'Brien!")));
}
}