django mvc,SpringMvc-MockMvc

 2023-10-15 阅读 31 评论 0

摘要: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.ann
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"));}}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/137124.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息