java+mock+例子_MOCK 基本使用例子

package com.icil.esolution.orders;

importstaticorg.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;

importstatic org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import org.apache.commons.httpclient.Header;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.methods.multipart.FilePart;

import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;

import org.apache.commons.httpclient.methods.multipart.Part;

import org.apache.commons.httpclient.methods.multipart.StringPart;

import org.apache.commons.io.FileUtils;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.slf4j.MDC;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.http.MediaType;

import org.springframework.mock.web.MockMultipartFile;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.MvcResult;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;

import com.alibaba.fastjson.JSON;

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

import com.icil.esolution.pojo.InventoryQueryVO;

import com.icil.esolution.pojo.SOOrderVO;

import com.icil.esolution.pojo.TOA;

import com.icil.esolution.utils.JsonUtils;

import com.icil.esolution.utils.URLHttpUtils;/**

*

* @ClassName: OrderControllerTest

* @Description:

* @Author: Sea

* @Date: 12 july 2018 5:02:06 PM

* @Copyright: 2018 ICIL All rights reserved.*/@RunWith(SpringRunner.class)

@SpringBootTestpublic classOrderControllerTest {

@AutowiredprivateWebApplicationContext wac;privateMockMvc mockMvc;

@Beforepublic voidSetup(){

mockMvc=MockMvcBuilders.webAppContextSetup(wac).build();

}

@Testpublic void TestQuerySOOrder() throws Exception {//customerCode, String warehouseCode

String result =mockMvc.perform(get("/order/querySOOrder")

.param("customer", "PDX000055")

.param("warehouseCode", "ULHKG")

.contentType(MediaType.APPLICATION_JSON_UTF8))

.andExpect(status().isOk())

.andReturn().getResponse().getContentAsString();

System.out.println(result);

}

@Testpublic voidtestUploadExcel() throws Exception {//File file = new File("/home/sea/Desktop/esolution/E+Outbound_Template.xls");//byte[] readFileToByteArray = FileUtils.readFileToByteArray(file);//String result = mockMvc.perform(fileUpload("/order/uploadExcel")//.file(new MockMultipartFile("ePlusExcel", "test.xls", "multipart/form-data", readFileToByteArray))//.param("warehouseCode", "ULHKG")//.param("customer","PDX000031"))//.andExpect(status().isOk())//.andReturn().getResponse().getContentAsString();//System.out.println(result);

File srcFile=new File("/home/sea/Desktop/esolution/Outbound_Template_eplus.xls");

String originalFileName=srcFile.getName();

InputStreamis = newFileInputStream(srcFile);//Upload excel template and return Order TO for confirmation

MockMultipartFile uploadFile = new MockMultipartFile("ePlusExcel",originalFileName , null, is);

MvcResult andReturn= mockMvc.perform(fileUpload("/order/uploadExcel").file(uploadFile).param("warehouseCode", "ULHKG").param("customer","PDX000031").accept("application/json;charset=UTF-8"))

.andExpect(status().isOk())

.andExpect(content().contentType("application/json;charset=UTF-8"))

.andReturn();

System.out.println(andReturn);

}/**

* POST方式 传带文件的调用

* @return

* @throws Exception*/@Testpublic voidPostMethodFileTest() throws Exception{

System.out.println("开始");

String targetUrl="http://localhost:8080/order/uploadExcel";

HttpClient client= newHttpClient();

PostMethod method= newPostMethod(targetUrl);try{

File srcFile=new File("/home/sea/Desktop/esolution/E+Outbound_Template.xls");

InputStream ePlusExcels= newFileInputStream(srcFile);

FilePart filePart= new FilePart("ePlusExcel",srcFile);//文件参数//new FilePart("ss", (PartSource) ePlusExcels);//StringPart ePlusExcel=new StringPart("ePlusExcel", ePlusExcels.toString());

StringPart customer= new StringPart("customer", "PDX000031");

StringPart warehouseCode=new StringPart("warehouseCode", "ULHKG");//method.setParameter("customer", "PDX000031");//method.setParameter("warehouseCode", "ULHKG");//StringPart questionId = new StringPart("questionId","10001");//普通参数//StringPart userId = new StringPart("userId","765709");//普通参数//StringPart homeworkId = new StringPart("homeworkId","950");//普通参数

Part[] parts={filePart,customer,warehouseCode};

MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams()); //封装了普通字段和文件字段

method.setRequestEntity(mre);int result =client.executeMethod(method);if (result ==HttpStatus.SC_OK) {

InputStreamin =method.getResponseBodyAsStream();

ByteArrayOutputStream baos= newByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = in.read(buffer)) != -1) {

baos.write(buffer,0, len);

}

String response= URLDecoder.decode(baos.toString(), "UTF-8");

System.out.println("response*****"+response);

}else{throw new Exception("HTTP ERROR Status:" + method.getStatusCode() + ":" +method.getStatusText());

}

}finally{

method.releaseConnection();

}

}

@Testpublic void testquerySOOrderDetail() throws Exception {//customerCode, String warehouseCode

String result =mockMvc.perform(get("/order/querySOOrderDetail")

.param("orderNo", "SO-HKG-00152542")

.param("warehouseCode", "ULHKG")

.contentType(MediaType.APPLICATION_JSON_UTF8))

.andExpect(status().isOk())

.andReturn().getResponse().getContentAsString();

System.out.println(result);

}

@Test

public voidtestQueryInventory() throws UnsupportedEncodingException, Exception{

String result= mockMvc.perform(get("/order/queryInventory")

.param("warehouseCode", "ULHKG")

.param("customerCode", "PDX000031")

.contentType(MediaType.APPLICATION_JSON_UTF8))

.andExpect(status().isOk())

.andReturn().getResponse().getContentAsString();

System.out.println(result);

}

@Testpublic voidtestName() throws Exception {

HashMap hashMap = new HashMap<>();

hashMap.put("aa", "ss");

String objectToJson=JsonUtils.objectToJson(hashMap);

System.out.println(objectToJson);

}

@Testpublic voidTestapiQueryOrderDetails() throws Exception {

Header header= URLHttpUtils.getBasicAuthorizationHeader("testmsg1", "123456");

String response= URLHttpUtils.getURLRequest("https://192.168.18.176/wosedi/ws/apiQueryOrderDetails?orderNo=SO-HK-00152542&warehouseCode=ULHKG", header);

String exception= MDC.get("concectException");

System.err.println("exception is ******************:"+exception);

System.out.println(response);

}

@Testpublic voidtestJsontoList() throws Exception {

File file= new File("src/test/java/resource/SoOrderVo.json");

String data=FileUtils.readFileToString(file);

System.err.println(data);//Object json = JSON.toJSON(data);//SoOrderVO soOrderVO = JSON.parseObject(data, SoOrderVO.class);//List jsonToList = JsonUtils.jsonToList(data, SoOrderVO.class);

Gson gson = newGson();//SoOrderVO fromJson = gson.fromJson(data, SoOrderVO.class);//List jsonToList =gson.fromJson(data, new TypeToken>() {}.getType());

List jsonToList = JsonUtils.gsonTOList(data, SOOrderVO.class);

System.out.println("result is :"+jsonToList);

}

@Testpublic voidtestQueryOrderAll() throws Exception {

File file= new File("src/test/java/resource/QueryOrderALL.json");

String data=FileUtils.readFileToString(file);

System.err.println(data);//Object json = JSON.toJSON(data);//SoOrderVO soOrderVO = JSON.parseObject(data, SoOrderVO.class);//List jsonToList = JsonUtils.jsonToList(data, SoOrderVO.class);

Gson gson = newGson();//SoOrderVO fromJson = gson.fromJson(data, SoOrderVO.class);

List jsonToList =gson.fromJson(data, new TypeToken>() {}.getType());

System.out.println("this is first data"+jsonToList.get(0));//List jsonToList = JsonUtils.gsonTOList(data, SoOrderVO.class);

System.out.println("result is :"+jsonToList);

}

@Testpublic voidtestGsontoList() throws Exception {

File file= new File("src/test/java/resource/inventoryQueryResponseData.json");

String data=FileUtils.readFileToString(file);

System.err.println(data);//Object json = JSON.toJSON(data);//SoOrderVO soOrderVO = JSON.parseObject(data, SoOrderVO.class);//List jsonToList = JsonUtils.jsonToList(data, SoOrderVO.class);

Gson gson = newGson();//SoOrderVO fromJson = gson.fromJson(data, SoOrderVO.class);//List jsonToList =gson.fromJson(data, new TypeToken>() {}.getType());

List jsonToList = JsonUtils.gsonTOList(data, InventoryQueryVO.class);

System.out.println("result is :"+jsonToList);

}

@Testpublic voidtestWOS4TOA() throws Exception {

File file= new File("src/test/java/resource/Wos4ResponseData.json");

String data= FileUtils.readFileToString(file,"UTF-8");

System.out.println(data);

Object json=JSON.toJSON(data);

TOA toa= JSON.parseObject(data, TOA.class);

System.out.println(toa.getResult());

System.out.println(toa.getMesgs());

System.out.println(toa.getData());

}

@Testpublic voidtestJDK8DataFormart() throws Exception {

DateTimeFormatter dateTimeFormater= DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");

LocalDateTime localDateTime=LocalDateTime.now();

Date date= newDate();

System.out.println("【----new date----】" +date);

System.out.println("【----未格式化之前----】" +localDateTime);

System.out.println("【----格式化之后----】"+dateTimeFormater.format(localDateTime));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值