最近两天认真学习了一下spring mvc和powermock结合对http请求进行单元测试,这里记录一下写成的demo
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.easymock.EasyMock;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* MockC测试类.
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MockTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private MockHttpServletRequest request;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
request = new MockHttpServletRequest();
}
@Test
public void testMock() throws Exception {
// 请求的URL
String url = "your.com/url";
// 期望的返回值
int expectedId = 10000;
String expectedUname = "12312312";
// 期望的返回值
List<Item> expectedList = new ArrayList<Item>();
Item item1 = new Item();
item1.setCode("12312312312312312321");
item1.setEndTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2017-12-30 00:00:00"));
item1.setId(1000000);
item1.setType(1);
expectedList.add(item1);
// mock一个Service对象,将check 方法进行了mock处理
Service serviceMock = EasyMock.createMock(Service.class);
EasyMock.expect(serviceMock.check(
EasyMock.anyObject(HttpServletRequest.class), EasyMock.anyObject(HttpServletResponse.class)))
.andReturn(expectedId).anyTimes();
// mock ClientApi对象,将调用红包服务的ClientApi.fetchList方法 mock
ClientApi clientApiMock = EasyMock.createMock(ClientApi.class);
EasyMock.expect(clientApiMock.fetchList(
EasyMock.eq(expectedUname),
EasyMock.anyInt(),
EasyMock.anyInt(),
EasyMock.anyBoolean()
)).andReturn(expectedList).anyTimes();
//结合spring 将mock的对象注入到controller里
MobileRedController controller = (MobileRedController)webApplicationContext.getBean("controller");
ReflectionTestUtils.setField(controller, "service", serviceMock);
ReflectionTestUtils.setField(controller, "clientApi", clientApiMock);
// 必须进行replay
EasyMock.replay(serviceMock);
EasyMock.replay(clientApiMock);
//PowerMock.replayAll();
RequestBuilder builder = MockMvcRequestBuilders
.post()
// 添加其他属性
//.requestAttr("interceptor_handle_user_id",1091085)
//.cookie(new Cookie("wallet_token", "039baf05-dec4-3ad8-9138-ef6961cacdad")
//.header("Host", "")
;
//请求的结果
MvcResult mvcResult = mockMvc.perform(builder).andExpect(status().isOk()).andDo(print()).andReturn();
String httpResponseString = mvcResult.getResponse().getContentAsString();
JSONObject resultJson = JSONObject.parseObject(httpResponseString);
Assert.assertThat(resultJson.getJSONArray("data").size(), Matchers.is(1));
}
}
版权声明:本文为sevenlater原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。