1.构建单元测试类步骤
- 对需要进行测试的类alt+enter,创建test类
- 在类上添加注解
@RunWith(SpringRunner.class) //在spring环境中运行 在使用所有注释前必须使用@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境
@SpringBootTest(classes = PersonaPortalApplication.class) //其中,classes属性指定启动类,SpringBootTest.WebEnvironment.RANDOM_PORT经常和测试类中@LocalServerPort一起在注入属性时使用。会随机生成一个端口号。
@AutoConfigureMockMvc @AutoConfigureMockMvc是用于自动配置MockMvc
- 自动装配 Mockmvc
- 在需要测试的方法里写入测试方法
- 创建RequestBuilder对象,封装 url 参数和参数类型
ex:RequestBuilder request = get("/tagdev/listTags") .param("tagId","5") .contentType(MediaType.APPLICATION_JSON_UTF8);
6.使用MockMvc对象发送请求 获得返回结果
2.test例子
package com.**
import com.**
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* @author zhaozheng
* @create 2019/2/14
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ‘自己的springboot启动类’.class)
@AutoConfigureMockMvc
public class TagDevControllerTest {
@Autowired
private MockMvc mvc;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void addTag() {
}
@Test
public void updateTag() {
}
@Test
public void listTag() throws Exception {
RequestBuilder request = get("Controller的url路径:去除application中的server.servlet.context-path=/**")
.param("tagId","5")
.contentType(MediaType.APPLICATION_JSON_UTF8);
String contentAsString = mvc.perform(request).andReturn().getResponse().getContentAsString();
System.out.println(contentAsString);
}
@Test
public void exportExcel() {
}
}