springboot-web進階(四)——單元測試


一、概述

  基礎知識,參考:https://www.cnblogs.com/ysw-go/p/5447056.html

二、springboot的單元測試

  1.入門測試類

    最重要的不要忘記類上面的依賴,以及類里面方法上的@Test(底層是jUnit)

package com.example.demo; import com.example.demo.service.GirlService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * GirlService測試類 * * @author zcc ON 2018/2/9 **/ @RunWith(SpringRunner.class) @SpringBootTest public class GirlServiceTest { @Autowired private GirlService girlService; @Test public void findOneTest() { Assert.assertEquals(new Integer(20), girlService.findOne(4).getAge()); } }

    這樣,就可以看到相關結果了:

    

    // 為了高大上一點,請不要再使用小白式的sout了,多使用斷言.

  2.使用IDEA自動生成測試類

    例如還是測試上面的service里的findOne,則通過在方法上右擊->Goto->Test

    

  3.controller的API單元測試

    同樣,在方法上右擊,Goto->Test,得到測試類

package com.example.demo.controller; import com.example.demo.SpringbootDemoApplicationTests; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.Assert.*; @AutoConfigureMockMvc public class GirlControllerTest extends SpringbootDemoApplicationTests { @Autowired private MockMvc mvc; @Test public void getList() throws Exception { // 測試狀態碼
        mvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()); } }

    使用單元測試還有一個用處是在打包是會自動跑單元測試,並會給出測試結果,失敗時將會報ERROR!

  還有其他測試選項,例如測試.content.string("abc"來測試返回內容),完整的API,參考:這里


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM