@SpringBootTest单元测试示例

该博客展示了如何使用Spring Boot的MockMvc进行单元测试,包括POST和GET请求的方法。在测试中,创建了ParamVo对象并设置了相关参数,然后发送JSON请求到指定API路径,检查响应状态并记录响应内容。
摘要由CSDN通过智能技术生成

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengzhe.open.module.vo.ParamVo;
import lombok.extern.slf4j.Slf4j;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.nio.charset.Charset;


@Slf4j
@SpringBootTest
@AutoConfigureMockMvc
class XXControllerTest {

	@Autowired
	private MockMvc mockMvc;

	@Autowired
	private ObjectMapper objectMapper;

	@Test
	void XXPostMethod() {
		ParamVo vo = new ParamVo();
		vo.setName("王德发");
		vo.setCompanyTel("0755-12546454545454");
		vo.setInvoiceTileType("B1");
		vo.setSendEmail("46578794564546456465456@qq.com");
		vo.setTaxNo("7897456464645454654412356465112");
		MvcResult mvcResult;
		try {
			mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/channels/XXPostMethod")
							.contentType(MediaType.APPLICATION_JSON)
							.content(objectMapper.writeValueAsString(vo))
							.accept(MediaType.APPLICATION_JSON)
					)
					.andExpect(MockMvcResultMatchers.status().isOk())
					.andReturn();
			//MvcResult默认编码是ISO-8859-1 手动转一下utf-8
			log.info(mvcResult.getResponse().getContentAsString(Charset.defaultCharset()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	void XXGetMethod () {
		MvcResult mvcResult;
		try {
			mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/channels/XXGetMethod")
							.accept(MediaType.APPLICATION_JSON)
							.param("name", "张三").param("pass", "123456")
							.accept(MediaType.APPLICATION_JSON))
					.andExpect(MockMvcResultMatchers.status().isOk())
					.andReturn();
			log.info(mvcResult.getResponse().getContentAsString(Charset.defaultCharset()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值