这类比较常用的测试类我们就直接做一个Base封装好,可以在测试的时候更好的看核心部分
package com.alumni_circle.core.junit;
import com.alumni_circle.JunitTest;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author 龙小虬
* @since 2020-07-08 21:10
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextConfiguration(locations={"classpath:mybatis-config.xml","classpath:mvc-dispatcher.xml","classpath:applicationContext.xml"})
@ComponentScan(basePackages={"com.alumni_circle.controller", "com.alumni_circle.service"})
public class BaseJunit {
private static final Logger log = Logger.getLogger(JunitTest.class);
@Autowired
WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
/**
* 初始化SpringmvcController类测试环境
*/
@Before
public void setup(){
//加载web容器上下文
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
然后用其子类继承BaseJunit
package com.alumni_circle;
import com.alumni_circle.core.junit.BaseJunit;
import org.junit.Test;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author 龙小虬
* @since 2020-07-08 01:29
*/
public class JunitTest extends BaseJunit {
//post请求需要的对象参数
String str = "{}";
@Test
public void testTest() throws Exception{
String responseString = mockMvc.perform
(
//请求的url,请求的方法是get
// get("/ac/selectByPageNumSize")
//数据的格式
// .contentType(MediaType.APPLICATION_JSON)
// //添加参数(可以添加多个)
// .param("id","1")
//请求的url,请求方法是POST
post("/gossip/select")
.contentType(MediaType.APPLICATION_JSON).content(str)
)
//返回的状态是200
.andExpect(status().isOk())
//打印出请求和相应的内容
.andDo(print())
//将相应的数据转换为字符串
.andReturn().getResponse()
.getContentAsString();
System.out.println("对象" + responseString);
}
}