使用MockMVC與Junit進行單體測試
阿新 • • 發佈:2017-09-17
eval mvc obj abs nco tps 測試 nal pub
1、pom.xml追加
junit
spring-test
2、測試共通類
@ContextConfiguration(locations = { "classpath:springframework/application-context.xml", "classpath:springframework/dispatcherservlet-servlet.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @Transactional abstract public class TestCommon {private static final Logger LOG = LogManager.getLogger(); private MockMvc mockMvc; @Autowired private WebApplicationContext wac; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } }
3、示例
public class MemberTest extends TestCommon {/** * 請求:新增,請求方式:POST */ @Test @Rollback(false) public void add() throws Exception { String uri = "/member/add"; Map<String, String> contentParams = new HashMap<>(); contentParams.put("name", "測試用姓名"); contentParams.put("sex", "男"); String jsonStr= new ObjectMapper().writeValueAsString(contentParams); MockHttpServletResponse response = mockMvc.perform( MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON_UTF8).content(jsonStr)) .andReturn().getResponse(); if (response.getStatus() != HttpServletResponse.SC_OK) { fail("Http" + response.getStatus()); } LOG.info(response.getContentAsString()); } }
4、如果想測試除post以外的請求,可以調用MockMvcRequestBuilders的get, put等方法
5、類似於URL中的“?page=2”的參數,可以調用MockMvcRequestBuilders的params方法
使用MockMVC與Junit進行單體測試