1、引入jar包
<!-- 测试工具包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.0.0</version> </dependency> <!-- 测试报告--> <dependency> <groupId>org.uncommons</groupId> <artifactId>reportng</artifactId> <version>1.1.4</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.testng</groupId> <artifactId>testng</artifactId> </exclusion> </exclusions>
2、测试类代码
ps: 可继承类: 1、AbstractTransactionalTestNGSpringContextTests:可添加事务管理,如需回滚测试数据等 2、AbstractTestNGSpringContextTests:不需要事务
@RunWith(SpringRunner.class) @WebAppConfiguration @SpringBootTest public class AAAADemoTest extends AbstractTransactionalTestNGSpringContextTests { MockMvc mockMvc; @Autowired WebApplicationContext wac; @BeforeMethod public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } /** * 接受参数为对象 * @throws Exception */ @Test @Rollback(true)//true:回滚,false:不回滚 public void testAdd() throws Exception{ BannerRequest bannerRequest = new BannerRequest(); bannerRequest.setBannerName("banner测试0"); bannerRequest.setStatus(0); bannerRequest.setImgUrl("http://www.img.cn/banner.img"); bannerRequest.setUrl("http://www.img.cn/banner.img"); String str = JSONObject.toJSONString(bannerRequest); MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/demo/1.0/banner/add") .contentType(MediaType.APPLICATION_JSON).content(str)) .andDo(MockMvcResultHandlers.print()) //增加一个结果处理器 .andExpect(MockMvcResultMatchers.status().isOk()) //执行完成后的断言 .andReturn(); //执行完成后返回相应的结果 String content = result.getResponse().getContentAsString(); JSONObject jsonObject = JSONObject.parseObject(content); Assert.assertEquals("K-000000",jsonObject.getString("code")); } /** * 接受参数为基本数据类型 * @throws Exception */ @Test @Rollback(true)//true:回滚,false:不回滚 public void testParam() throws Exception{ MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/demo/1.0/banner/add") .param("param-key","param-value") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andDo(MockMvcResultHandlers.print()) //输出请求、响应相关数据 .andExpect(MockMvcResultMatchers.status().isOk()) //预期状态码 .andReturn(); //返回相应的结果 String content = result.getResponse().getContentAsString(); JSONObject jsonObject = JSONObject.parseObject(content); Assert.assertEquals("K-01",jsonObject.getString("code")); } }
右键》run,至此就完成了,如多个测试类需生成测试报告,如下:
a. 在test目录添加testng.xml,右键run,报告会自动写到与target平级目录的test-output目录下
<?xml version="1.0" encoding="UTF-8"?> <suite name="test" parallel="true"> <test name="test" preserver-order="true"> <classes> <!--自己的测试类 --> <class name="com.qlh.sbc.suning.provider.impl.BannerControllerTest" /> </classes> <listeners> <listener class-name="org.uncommons.reportng.HTMLReporter" /> <listener class-name="org.uncommons.reportng.JUnitXMLReporter" /> </listeners> </test> </suite>