SpringBoot 中mockMVC测试

SpringBoot 中mockMVC测试

  • mockMVC可实现在非启动状态下测试Controller类
package cn.tedu.boot.demo.controller;

import org.junit.jupiter.api.Test;
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.jdbc.Sql;
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;


@SpringBootTest
@AutoConfigureMockMvc   //自动配置MockMvc
public class AdminControllerTests {
    @Autowired
    MockMvc mockMvc;  //Mock: 模拟

    @Sql("classpath:truncate.sql")
    @Sql("classpath:insert.sql")
    @Test
    public void testLoginSuccessfully() throws Exception{
        // 准备测试数据, 不需要封装
        String username = "test001";
        String password = "123456";
        // 请求路径,不需要写协议、服务器主机端口号
        String url = "/admins/login";
        mockMvc.perform(
                MockMvcRequestBuilders.post(url)  // 根据请求方式决定调用的方法
            	// 请求数据的文档类型, 例如:application/json; charset=utf-8
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)  
            	// 请求参数,有多个时,多次调用param()方法
                .param("username",username)  
                .param("password",password)
           	 	// 接受的响应结果的文档类型,注意:perform()方法到此结束
                .accept(MediaType.APPLICATION_JSON)) 
            	// 预判结果,类似断言
                .andExpect( 
                        MockMvcResultMatchers
                        .jsonPath("state") //预判响应的JSON结果中将会有名为state的属性\
            			//预判响应的JSON结果中名为state的属性的值,注意: andException()方法到此结束
                        .value(200)) 
                .andDo( // 需要执行某任务
                        MockMvcResultHandlers.print()); // 打印日志

    }
}

在执行以上代码时,响应的JSON中如果包含中文,可能会出现乱码,需要在配置文件(application.propertiesapplication.yml中配置)中添加配置。

.properties文件中:

server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8

.yml文件中:

server:
  servlet:
    encoding:
      force: true
      charset: utf-8

你可能感兴趣的:(#,工具,spring,boot,java,后端)