在寫SpringBoot項目時用到了單元測試功能,來測試Service和Controller很方便,簡單記錄一下
pom.xml 文件里面添加兩個測試擴展包:
... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> ...
創建一個User的實體類:
package com.demo.www.model.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * 用戶表 * @author AnYuan */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("users") public class User implements Serializable { @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 用戶名 */ private String name; /** * 手機號 */ private String phone; }
創建一個UserService:
package com.demo.www.service; import com.baomidou.mybatisplus.extension.service.IService; import com.demo.www.model.entity.User; /** * 用戶表 服務類 * @author AnYuan */ public interface UserService extends IService<User> { }
最后創建一個Controller:
package com.demo.www.controller; import com.demo.www.model.entity.User; import com.demo.www.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * 用戶Controller * @author AnYuan */ @Slf4j @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{id}") public User getUser(@PathVariable String id) { return userService.getById(id); } }
接口寫好之后,創建一個測試類。如過使用IDEA開發的話,點擊需要測試的類,command + shift 鍵即可生成對應的測試類。
這里配置 @AutoConfigureMockMvc 注解自動注入 MockMvc 類進行測試。使用該注解可以不啟動 tomcat 服務器,但啟動Spring應用的程序,再使用mockMvc進行http請求測試
package com.demo.www.controller; import org.hamcrest.core.StringContains; import org.junit.Test; import org.junit.runner.RunWith; 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.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class UserControllerTest { @Autowired private MockMvc mockMvc; /** * * perform : 執行MockMvcRequestBuilders的請求並返回一個類型,該類型結果可以鏈式操作。 * MockMvcRequestBuilders請求的類型包括:get(),post(),put(),delete()。 * * accept : 希望接收的數據類型 * header : 表明請求客戶端類型 * param : 請求參數 * ... * * andExpect : 添加 MockMvcResultMatchers 的結果驗證器。可以判斷http狀態碼和返回json是否為包含期望值 * andDo: 添加 MockMvcResultHandlers 的結果處理器,可以打印返回的內容 */ @Test public void getUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .accept(MediaType.APPLICATION_JSON) .header("X-Client", "app") .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(StringContains.containsString("age"))) .andDo(MockMvcResultHandlers.print()) .andReturn(); } }
最后執行該測試方法,正常情況下控制台輸出:
Url不存在異常:
返回的數據里面沒有包含期望的字符串異常:
以上就是SpringBoot里簡單測試Controller,除了使用MockMvc,還可以注入 TestRestTemplate 來使用http的請求測試。
如果要測試Service層,可以直接注入Servic服務,在Test類的方法里面調用Service的方法。
Spring官方測試用例:https://spring.io/guides/gs/testing-web/