feat(v1): unify API response, validation, exception handling and tests
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class UserControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
void shouldListUsersWithApiResponseWrapper() throws Exception {
|
||||
mockMvc.perform(get("/api/users"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldCreateUser() throws Exception {
|
||||
String json = """
|
||||
{
|
||||
\"name\": \"测试用户\",
|
||||
\"email\": \"test@example.com\",
|
||||
\"age\": 22
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data.name").value("测试用户"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRejectInvalidUser() throws Exception {
|
||||
String json = """
|
||||
{
|
||||
\"name\": \"\",
|
||||
\"email\": \"bad-mail\",
|
||||
\"age\": 222
|
||||
}
|
||||
""";
|
||||
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value(400));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user