1.寫一個父類
package 你的包;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;import java.nio.charset.Charset;import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTestCase extends AbstractJUnit4SpringContextTests{public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));@Autowiredprotected WebApplicationContext wac;protected MockMvc mockMvc;@Beforepublic void setup() throws Exception {this.mockMvc = webAppContextSetup(this.wac).build();}
}
2.測試類繼承上邊的類,下面是一個測試登錄的集成測試,模擬發送HTTP post請求
package 包名;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;import org.junit.Assert;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;import com.alibaba.fastjson.JSONObject;public class LoginTest2 extends SpringTestCase{@Testpublic void test() throws Exception {JSONObject param = new JSONObject();param.put("mobile", "16156536563");param.put("password", "mima");String actual = param.toJSONString();System.out.println("============param===>" + actual);MvcResult mvcResult = this.mockMvc.perform(post("/login").characterEncoding("UTF-8") .contentType(MediaType.APPLICATION_JSON).content(actual).header("deviceId", "bb")).andDo(print()).andReturn();int status = mvcResult.getResponse().getStatus();Assert.assertEquals(200, status); String result = mvcResult.getResponse().getContentAsString(); JSONObject jsonObject = JSONObject.parseObject(result); Assert.assertEquals(true, jsonObject.containsKey("result"));Assert.assertEquals(true, jsonObject.containsKey("resultCode"));Assert.assertEquals(true, jsonObject.containsKey("resultMessage"));Assert.assertEquals(true, jsonObject.containsKey("data"));}}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态