/** * Created by William on 2017/12/17. */ //表示使用Spring Test組件進行單元測試,其中SpringRunner繼承類SpringJUnit4ClassRunner。 @RunWith(SpringRunner.class) @SpringBootTest //注入一個MockMvc實例; @AutoConfigureMockMvc //測試環境使用,用來表示測試環境使用的ApplicationContext將是WebApplicationContext類型的;value指定web應用的根; @WebAppConfiguration public class VisitRecordServiceTest { @Autowired private WebApplicationContext context; @Resource private VisitRecordService visitRecordService; private MockMvc mockMvc; @Before public void setUp() { //注入web環境的ApplicationContext容器:mvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testAll() { testCreate(); testQuery(); } @Test public void testCreate() { VisitRecord visitRecord = new VisitRecord(); Salesman salesman = new Salesman("5ab44390d282422c897d643e41bbb32f"); visitRecord.setSalesman(salesman); visitRecord.setOrganizationName("xxx網咖"); visitRecord.setAreaProvince(new Area("440000")); visitRecord.setAreaCity(new Area("441300")); visitRecord.setAreaDistrict(new Area("441303")); visitRecord.setAddress("東莞大道123號"); visitRecord.setContactPerson("張某某"); visitRecord.setContactPhone("18655556666"); visitRecord.setGpsLat(22.98879); visitRecord.setGpsLng(113.72551); visitRecord.setNote("這家商家有點興趣使用友競Club,下月再來拜訪一次"); List<Picture> pictures = new ArrayList<>(); pictures.add(new Picture("第一章照片", "image/food-default.jpg", Constants.STATUS_NORMAL)); visitRecord.setPictures(pictures); this.visitRecordService.create(visitRecord); } @Test public void testQuery() { VisitRecordQueryParam queryParam = new VisitRecordQueryParam(); queryParam.setSalesmanId("5ab44390d282422c897d643e41bbb32f"); List<VisitRecord> visitRecords = this.visitRecordService.queryList(queryParam); System.out.println("size:" + visitRecords.size()); } @Test public void testGet() throws Exception { mockMvc.perform( MockMvcRequestBuilders.get("/visitrecord") .param("salesmanId", "5ab44390d282422c897d643e41bbb32f") ).andDo(print()); } @Test public void testPost() throws Exception { int random = new Random().nextInt(100); mockMvc.perform( MockMvcRequestBuilders.post("/visitrecord") .param("wechatUserId", "5c8cb3aa0a58417f943146051a037b19") .param("organizationName", "xx網咖" + random) .param("areaProvince.id", "440000") .param("areaCity.id", "441300") .param("areaDistrict.id", "441303") .param("address", "東莞大道" + random + "號") .param("contactPerson", "張某某" + random) .param("contactPhone", (18566660000L + random) + "") .param("gpsLat", "22.98" + random) .param("gpsLng", "113.72" + random) .param("note", "這家商家有點興趣使用友競Club,下月再來拜訪一次" + random) .param("pictures[0].url", "image/food-default.jpg") ).andDo(print()); } }