SpringBoot + Junit5 + MockMvc 寫單元測試


 1.1  junit5  版本5.6.0  pom文件如下:

<properties>
    <junit.jupiter.version>5.6.0</junit.jupiter.version>
</properties>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>${junit.jupiter.version}</version>
    <scope>test</scope>
</dependency>

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

  

1.2 test 測試類里面  首先先構建mockMvc的環境

@SpringBootTest
@ExtendWith(SpringExtension.class) //導入Spring測試框架
@DisplayName("人員ctr測試")
public class PersonControllerTest {


    @Autowired
    private PersonController personController ;

    private MockMvc mockMvc;



    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);//這句話執行以后,service自動注入到controller中。
        // (1)構建mvc環境
        mockMvc = MockMvcBuilders.standaloneSetup((personController)).build();
    }
}

  

 

 

 

  1.3  開始編寫測試方法  

    1.2.1  Junit5最大的變化就是可以傳參 ,簡單介紹一下用法

         @ValueSource(strings = {"111","222"}) //多個參數執行多次(即id為111執行一次后還會執行id為222) ,參數為字符串類型 public void test(String id){}
       @MethodSource("getPerson")  //參數為方法,方法里面你可以寫你想要的數據格式 ,比如getPerson返回的JSONObject格式 public void test(JSONObject jsonobject){}
         @ParameterizedTest //需要傳參數時需要使用, 跟上面的注解是配套用的


   1.2.2 MockMvc的使用:模擬對象去調用,真正實現單元測試

       1. mockMvc.perform(MockMvcRequestBuilders.get("/v1/user/get_info") //請求構建mvc環境時的controller層里面的地址 , 可以get、post、put請求

       2. .contentType(MediaType.APPLICATION_FORM_URLENCODED) //設置內容格式 ,當為post請求時要使用 .accept()設置接收格式,和內容的格式一樣

       3. post傳參使用 .content(JSONObject.toJSONString(personIds))//設置內容

       

@Test
    @DisplayName("根據id_獲取人員信息")
    @Order(1) //順序
   // @MethodSource("getPerson")  //參數為方法
    @ValueSource(strings = {"111","222"}) //多個參數執行多次
    @ParameterizedTest //需要傳參數時使用
    public void getPersonById(String id) throws Exception {
      

        MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.get("/v1/person/get_info")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED) //設置內容格式
                .param("personid",id)//設置內容
                )
                .andDo(MockMvcResultHandlers.print())//返回打印結果
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse();
        response.setCharacterEncoding("UTF-8"); //解決中文亂碼問題

        Result<PersonDTO> result = JSONObject.parseObject(response.getContentAsString(), Result.class);//反序列化成對象
        Assertions.assertTrue(result.getDataStore() != null);  //斷言結果校驗
    }

  

1.4 測試成功

 


免責聲明!

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



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