SpringBoot2.0實戰(zhàn) | 第三章:SpringBoot單元測試

本章目標(biāo)

基于上一章,使用單元測試實現(xiàn)對增刪查改接口的測試

操作步驟

添加依賴

引入 spring-boot-starter-test 的依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

添加依賴后的整體 dependencies 如下所示

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

編碼

測試用例編寫在 src/test/java 源目錄下

  1. 編寫測試用例
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
public class UserTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private UserRepository userRepository;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testInsert() throws Exception {
        MvcResult mvcResult = mvc.perform(
                MockMvcRequestBuilders
                .post("/user/add")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content("{\"name\":\"user1\",\"sex\":1,\"birthday\":\"2000-05-21\"}")
        )
//        .andExpect(status().isOk());
//        .andExpect(content().string("hello"))
        .andDo(MockMvcResultHandlers.print())
        .andReturn();

        Assert.assertEquals(200, mvcResult.getResponse().getStatus());
    }

}
  • 注解分析
@RunWith(SpringRunner.class) // 指定 SpringRunner 作為單元測試的執(zhí)行類,SpringRunner 是 spring-test 提供的測試執(zhí)行單元類
@WebAppConfiguration         // 模擬 ServletContext
@SpringBootTest(classes = Application.class) // 指定測試啟動類,配置文件以及環(huán)境
  • MockMvc 用于向 controller 接口發(fā)起模擬請求
  • @Before 會在測試用例執(zhí)行之前執(zhí)行,在本例中用于初始化環(huán)境
  • @Test 標(biāo)記當(dāng)前方法是需要執(zhí)行的測試用例

驗證結(jié)果

選擇測試用例,右鍵選擇 Run

源碼地址

本章源碼 : https://gitee.com/gongm_24/spring-boot-tutorial.git

總結(jié)

請為自己的所有方法編寫單元測試

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容