SpringBoot 如何使用 MockMvc 進(jìn)行 Web 集成測(cè)試
介紹
SpringBoot 是一個(gè)流行的 Java Web 開發(fā)框架,它提供了一些強(qiáng)大的工具和庫,使得開發(fā) Web 應(yīng)用程序變得更加容易。其中之一是 MockMvc,它提供了一種測(cè)試 SpringBoot Web 應(yīng)用程序的方式,可以模擬 HTTP 請(qǐng)求和響應(yīng)的行為。
在本文中,我們將介紹 SpringBoot 中的 MockMvc,演示如何使用它進(jìn)行 Web 集成測(cè)試。
MockMvc
MockMvc 是 SpringFramework 中的一個(gè)測(cè)試工具,用于模擬 HTTP 請(qǐng)求和響應(yīng)的行為。MockMvc 可以模擬發(fā)送 GET、POST、PUT、DELETE 等 HTTP 請(qǐng)求,并驗(yàn)證響應(yīng)的狀態(tài)碼、內(nèi)容類型和響應(yīng)體等。
在 SpringBoot 中,我們可以使用 MockMvc 進(jìn)行 Web 集成測(cè)試。下面是一個(gè)簡(jiǎn)單的例子:
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUser() throws Exception {
mockMvc.perform(get("/users/{id}", 1))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.age").value(25));
}
}
在上面的代碼中,我們使用 @SpringBootTest 和 @AutoConfigureMockMvc 注釋 SpringBoot 應(yīng)用程序和 MockMvc。然后,我們使用 @Autowired 注釋注入 MockMvc 對(duì)象。最后,我們使用 perform 方法模擬發(fā)送 GET 請(qǐng)求,并使用 andExpect 方法驗(yàn)證響應(yīng)的狀態(tài)碼、內(nèi)容類型和響應(yīng)體等。
如何使用 MockMvc 進(jìn)行 Web 集成測(cè)試
要使用 MockMvc 進(jìn)行 Web 集成測(cè)試,請(qǐng)按照以下步驟操作:
第 1 步:添加依賴
在 pom.xml 文件中添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
在上面的代碼中,我們添加了一個(gè) spring-boot-starter-test 依賴,它包含了許多測(cè)試相關(guān)的依賴。
第 2 步:?jiǎn)⒂?MockMvc
在測(cè)試類中添加 @SpringBootTest 和 @AutoConfigureMockMvc 注釋啟用 MockMvc。
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
...
}
在上面的代碼中,我們使用 @SpringBootTest 注釋啟用 SpringBoot 應(yīng)用程序,并使用 @AutoConfigureMockMvc 注釋啟用 MockMvc。
第 3 步:注入 MockMvc 對(duì)象
在測(cè)試類中使用 @Autowired 注釋注入 MockMvc 對(duì)象。
@Autowired
private MockMvc mockMvc;
在上面的代碼中,我們使用 @Autowired 注釋注入 MockMvc 對(duì)象。
第 4 步:模擬 HTTP 請(qǐng)求
使用 MockMvc 對(duì)象的 perform 方法模擬 HTTP 請(qǐng)求。
mockMvc.perform(get("/users/{id}", 1))
在上面的代碼中,我們使用 get 方法模擬發(fā)送 GET 請(qǐng)求。在路徑中使用占位符 {id},可以在后面的參數(shù)列表中指定實(shí)際的 id 值。
第 5 步:驗(yàn)證響應(yīng)狀態(tài)碼
使用 andExpect 方法驗(yàn)證響應(yīng)的狀態(tài)碼。
.andExpect(status().isOk())
在上面的代碼中,我們使用 status 方法獲取響應(yīng)的狀態(tài)碼,并使用 isOk 方法驗(yàn)證狀態(tài)碼是否為 200。
第 6 步:驗(yàn)證響應(yīng)內(nèi)容類型
使用 andExpect 方法驗(yàn)證響應(yīng)的內(nèi)容類型。
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
在上面的代碼中,我們使用 content 方法獲取響應(yīng)的內(nèi)容類型,并使用 contentType 方法驗(yàn)證內(nèi)容類型是否為 JSON。
第 7 步:驗(yàn)證響應(yīng)體
使用 andExpect 方法驗(yàn)證響應(yīng)的內(nèi)容。
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.age").value(25));
在上面的代碼中,我們使用 jsonPath 方法獲取響應(yīng)體中的 JSON 屬性,并使用 value 方法驗(yàn)證屬性的值是否正確。
示例
以下是一個(gè)完整的示例:
UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
private List<User> users = new ArrayList<>();
@GetMapping("/{id}")
public User getUser(@PathVariable int id) {
return users.stream()
.filter(user -> user.getId() == id)
.findFirst()
.orElse(null);
}
@PostMapping
public User createUser(@RequestBody User user) {
int nextId = users.size() + 1;
user.setId(nextId);
users.add(user);
return user;
}
@PutMapping("/{id}")
public User updateUser(@PathVariable int id, @RequestBody User user) {
User existingUser = users.stream()
.filter(u -> u.getId() == id)
.findFirst()
.orElse(null);
if (existingUser != null) {
existingUser.setName(user.getName());
existingUser.setAge(user.getAge());
}
return existingUser;
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id) {
users.removeIf(user -> user.getId() == id);
}
}
UserControllerTest.java
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUser() throws Exception {
mockMvc.perform(get("/users/{id}", 1))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.age").value(25));
}
@Test
public void testCreateUser() throws Exception {
User user = new User();
user.setName("Jane Doe");
user.setAge(30);
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").isNumber())
.andExpect(jsonPath("$.name").value("Jane Doe"))
.andExpect(jsonPath("$.age").value(30));
}
@Test
public void testUpdateUser() throws Exception {
User user = new User();
user.setName("Jane Doe");
user.setAge(30);
mockMvc.perform(put("/users/{id}", 1)
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("Jane Doe"))
.andExpect(jsonPath("$.age").value(30));
}
@Test
public void testDeleteUser() throws Exception {
mockMvc.perform(delete("/users/{id}", 1))
.andExpect(status().isOk());
mockMvc.perform(get("/users/{id}", 1))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
private String asJsonString(Object obj) {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
在上面的示例中,我們創(chuàng)建了一個(gè) UserController 類,并實(shí)現(xiàn)了 GET、POST、PUT 和 DELETE 方法。然后,我們創(chuàng)建了一個(gè) UserControllerTest 類,并使用 MockMvc 對(duì)象模擬發(fā)送 HTTP 請(qǐng)求,并驗(yàn)證響應(yīng)的狀態(tài)碼、內(nèi)容類型和響應(yīng)體等。我們還定義了一個(gè) asJsonString 方法,用于將對(duì)象轉(zhuǎn)換為 JSON 字符串。文章來源:http://www.zghlxwxcb.cn/news/detail-596439.html
結(jié)論
使用 MockMvc 進(jìn)行 Web 集成測(cè)試是一種方便快捷的方式,可以有效地測(cè)試 SpringBoot Web 應(yīng)用程序的功能。在本文中,我們介紹了 MockMvc 的基本概念和用法,并演示了如何使用 MockMvc 進(jìn)行 Web 集成測(cè)試。如果你正在開發(fā) SpringBoot Web 應(yīng)用程序,建議你使用 MockMvc 進(jìn)行集成測(cè)試,以確保你的應(yīng)用程序能夠正常工作。文章來源地址http://www.zghlxwxcb.cn/news/detail-596439.html
到了這里,關(guān)于SpringBoot 如何使用 MockMvc 進(jìn)行 Web 集成測(cè)試的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!