Junit 模拟http请求快速上手

本文介绍如何在SpringBoot项目中使用JUnit4进行HTTP测试,包括配置、MockMvc对象初始化及测试代码示例。适用于快速入门,了解如何进行接口测试。

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

junit相信做java的都不陌生,用过的人也很多。本人一直没写过junit的http测试,最近有用到,网上的资料不少,但是比较杂。所以整理一个让你快速开始写代码的文章。本文属于快速入门使用,不属于深入研究类型。

本文是基于springboot,junit4

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RouterApplication.class) // 这个是你的springboot启动类
@ActiveProfiles("junit") // 这个是你使用的配置文件profile。一般都会使用多套配置文件,和开发,生产的配置区分开
public class Tests {

    @Autowired
    protected WebApplicationContext wac;

    protected MockMvc mockMvc;

    @Before
    public void setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
    }

    @Test
    public void testMockMvc() throws Exception{
       //post请求
        MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/deliver"); //  接口路径
        post.content(reqStrDemo.getBytes("UTF-8"));

        String string = mockMvc.perform(post).andReturn().getResponse().getContentAsString();
        System.out.println(string);
    }
}

或者还有一种写法。本人使用的是下面这种方法。两种方式都自测过,都可以。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RouterApplication.class) // 这个是你的springboot启动类
@ActiveProfiles("junit") // 这个是你使用的配置文件profile。一般都会使用多套配置文件,和开发,生产的配置区分开
public class Tests {

    @Autowired
    protected TestController controller; // 把要测试的controller注入进来

    @Test
    public void test() throws Exception{
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setContent(xxxxxxx); // 直接设置请求内容(post),参数等也在request里设置
        MockHttpServletResponse response = new MockHttpServletResponse();

		controller.testMethod(request, response)
        String string = response.getContentAsString();
        System.out.println(string);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值