controller层的单元测试
Base的测试类,其他所有测试类继承这个类:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import st.context.ContextConfiguration;
import st.context.junit4.SpringJUnit4ClassRunner;
import st.context.web.WebAppConfiguration;
import st.web.servlet.MockMvc;
import st.web.servlet.setup.MockMvcBuilders;
import org.t.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class) //使⽤junit4进⾏测试
@ContextConfiguration(locations = {"l","classpath:conf/l", "classpath:l"}) @WebAppConfiguration
public class BaseUnit {
protected MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before()
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象
}
@Before
public void before() {
}
@Test
public void test() throws Exception {
}
}
主测试类⾥⾯引⼊springmvc的配置,同时需要加上注解@WebAppConfiguration,
然后单侧⾥⾯使⽤mockMvc模拟请求即可:
@Slf4j
public class TestControllerTest extends BaseUnit {
private String uri = "/test";
@Test
public void test1() throws Exception {
ResultActions resultActions = kMvc
.perform(MockMvcRequestBuilders.post(uri + "/test1")
.param("ip", "192.168.1.1")
.param("user", "aaa")
.param("password", "bbb")
.accept(MediaType.APPLICATION_JSON_VALUE));
MvcResult mvcResult = resultActions.andReturn();
String result = Response().getContentAsString();
<("返回的数据:" + result);
}
}
这边修改请求的⽅法类型:get请求就get,put就put.参数的话,如果是json的话,就.content().
mybatis和springmvc
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论