SpringBoot测试基类包括mockMvc使用get和post请求

SpringBoot测试基类

  • 类上方
  • 类中必填信息

类上方

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DshareApplication.class)(class名填写你的启动类名)
@WebAppConfiguration

类中必填信息

@Autowired
public MockHttpSession session;

@Autowired
public WebApplicationContext wac;

public MockMvc mockMvc;

@Before
public void setup() throws Exception {
	this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
	session.setAttribute(UserConstants.CURR_LOGIN_USER, user);//session存放用户信息
}

/**
*用于json格式的数据格式化
/
public static String formatJson(String jsonStr) {
	if (null == jsonStr || "".equals(jsonStr))
		return "";
	StringBuilder sb = new StringBuilder();
	char last = '\0';
	char current = '\0';
	int indent = 0;
	for (int i = 0; i < jsonStr.length(); i++) {
		last = current;
		current = jsonStr.charAt(i);
		switch (current) {
		case '{':
		case '[':
			sb.append(current);
			sb.append('\n');
			indent++;
			addIndentBlank(sb, indent);
			break;
		case '}':
		case ']':
			sb.append('\n');
			indent--;
			addIndentBlank(sb, indent);
			sb.append(current);
			break;
		case ',':
			sb.append(current);
			if (last != '\\') {
				sb.append('\n');
				addIndentBlank(sb, indent);
			}
			break;
		default:
			sb.append(current);
		}
	}

	return sb.toString();
}

private static void addIndentBlank(StringBuilder sb, int indent) {
	for (int i = 0; i < indent; i++) {
		sb.append('\t');
	}
}
--------------------------------post和get请求方式---------------------------------
String uri = "/api/article/sharedList";
	// String contentAsString =
	// this.mockMvc.perform(post(uri).session(session)).andExpect(status().isOk()).andReturn()
	// .getResponse().getContentAsString(); //post请求
	String contentAsString = this.mockMvc  
			.perform(MockMvcRequestBuilders.get(uri).param("tenantId", "1").param("toTenantId", "2"))
			.andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); //get请求


----------------------------json格式的字符串------------------------------------
			string json = "[{\"a\":\"111\",\"b\":\"222\",\"c\":\"333\"},{\"a\":\"1000\",\"b\":\"2000\",\"c\":\"000\"},{\"a\":\"999\",\"b\":\"300\",\"c\":\"700\"}]";

你可能感兴趣的:(SpringBoot测试基类包括mockMvc使用get和post请求)