sprinboot 自动化测试程序

maven 依赖

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

测试程序

模拟请求过程,设置期望结果:不符合结果的报错、失败,说明接口还有问题

import java.util.HashMap;
import java.util.Map;

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.MockMvcResultMatchers;

import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmartshopApplication.class)
@AutoConfigureMockMvc
public class SmartshopApplicationTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testMockUsage() throws Exception {
        ObjectMapper jsonMapper = new ObjectMapper();
        // 获取请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("mobile", "13100001111");
        requestBody.put("password", "123456");
        String requestBodyStr = jsonMapper.writeValueAsString(requestBody);
        // 获取响应体
        Map<String, String> responseBody = new HashMap<>();
        responseBody.put("result_desc", "登录成功");
        String responseBodyStr = jsonMapper.writeValueAsString(responseBody);
        // 模拟请求过程,设置期望结果:不符合结果的报错、失败,说明接口还有问题
        String returnContent = mockMvc.perform(MockMvcRequestBuilders.post("/api/login")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(requestBodyStr))
                // 设置对返回内容的要求:成功
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().json(responseBodyStr))
                // 获取返回体内容
                .andReturn().getResponse().getContentAsString();
        System.out.println(returnContent);
    }
}

可结合gradle build,批量测试接口,生成测试报表,查看错误信息:gradle的配置与使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值