Junit 测试 Rest 接口的两种方式

本文介绍了两种使用Junit测试Spring MVC Rest接口的方法:一是通过RestTemplate模式,该方法需要启动服务器;二是利用MockMvc模式,此模式下无需启动服务器。在构建项目时,添加相关依赖并配置,如使用Flyway进行数据初始化。测试过程中,使用H2内存数据库确保每次测试都有新的数据库环境,避免影响实际的MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:RestTemplate模式 需要启动服务器

@Test
    public void restTemplate() throws Exception{
        String user = "{\"id\":10,\"password\":\"myPassword\",\"userName\":\"myUserName\"}";//实例请求参数
        HttpHeaders headers = new HttpHeaders();//创建一个头部对象
        //设置contentType 防止中文乱码
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
        //设置我们的请求信息,第一个参数为请求Body,第二个参数为请求头信息
        //完整的方法签名为:HttpEntity<String>(String body, MultiValueMap<String, String> headers)
        HttpEntity<String> strEntity = new HttpEntity<String>(user,headers);
        RestTemplate restTemplate  = new RestTemplate();
        //使用post方法提交请求,第一参数为url,第二个参数为我们的请求信息,第三个参数为我们的相应放回数据类型,与String result对厅
        //完整的方法签名为:postForObject(String url, Object request, Class<String> responseType, Object... uriVariables) ,最后的uriVariables用来拓展我们的请求参数内容。
        String result = restTemplate.postForObject("http://localhost:8080/springMVC/user/getUser1",strEntity,String.class);
        System.out.println(result);//运行方法,这里输出:
    }

二:MockMvc模式  无需启动服务器

  1. 构建项目--pom里面一些关键的依赖包

<!--用于数据库管理-->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
</dependency>
<!--测试依赖包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!--内存数据库用于测试-->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

 

  • spirng boot提供了测试框架我们只要引入spring-boot-starter-test 就可以了。
  • spirng boot还集成了flyway flyway简单入门,我们可以用这个工具来帮我们初始化测试用的数据表。 当然不用flywayhibernate也有反向生成数据表的功能
  • H2是一个免安装内嵌在运行程序里的一个数据库,这里我用它来作为我们的单元测试使用的数据库。这个数据库运行在内存中生命周期与单元测试生命周期一样。也就是说每次运行都是新的库。单元测试的数据是不会写到mysql库里的。
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class UserControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        @Test
        public void test() throws Exception {
            RequestBuilder request;
    
            // 1、get查一下user列表应该为空
            request = get("/user");
            mvc.perform(request)
                    .andExpect(status().isOk())
                    .andExpect(content().string(equalTo("[]")));
            // 2、post提交一个user
            request = post("/user/")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content("{\"name\":\"zxc\",\"age\":18}");
            mvc.perform(request)
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.name",is("zxc")));
            // 3、get查一下user列表,应该不为空
            request = get("/user");
            mvc.perform(request)
                    .andExpect(status().isOk())
                    .andExpect(content().string(not("")))
                    .andExpect(content().string(not("[]")));
            // 4、get查一下user id 等于1的用户,应该不为空,age等于18
            request = get("/user/{id}",1);
            mvc.perform(request)
                    .andExpect(status().isOk())
                    .andExpect(content().string(not("")))
                    .andExpect(jsonPath("$.age").value(18));
    
            // 4、put更新用户zxc
            request = put("/user")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content("{\"id\":1,\"name\":\"zxc\",\"age\":20}");
            mvc.perform(request)
                    .andExpect(status().isOk())
                    .andDo(print())
                    .andExpect(jsonPath("$.age").value(20))
                    .andExpect(jsonPath("$.name").value("zxc"));
        }
    }
    

    参考地址:https://www.jianshu.com/p/eaa7f17d7def

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值