Soap文件转对象,用于Junit

测试用类
package test.com.coverage.facade;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;

import test.com.coverage.CoverageBase;

import com.common.facade.TransManageFacade;
import com.common.facade.bean.TransRefundReq;
import com.common.facade.bean.TransRefundRes;
import com.common.facade.constants.SysRetCodeConstants;


public class TestManageTransRefund  extends CoverageBase
{
    public static String FILE_PREFIX="/soapUI/facade";

    @Resource(name="transManageFacade")
    public  TransManageFacade transManageFacade;
    
    @Test
    public void testRefund() throws Exception 
    {
        String xmlFile = FILE_PREFIX+"/refundRequest.xml";
        Map<String,String> param=new HashMap<String,String>();
        param.put("orderNo",Long.toString(System.currentTimeMillis()));
        TransRefundReq req = super.parseRequest(xmlFile,param,TransRefundReq.class);
        TransRefundRes res = transManageFacade.manageTransRefund(req);
        Assert.assertSame(SysRetCodeConstants.SYSTEM_ERROR.getCode(), res.getRespCode());
    }
}

引入上线文的类
package test.com.coverage;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( {
	"classpath*:/spring/applicationContext-load-config.xml",
	"classpath*:/spring/applicationContext*.xml",
	"classpath*:/spring/datasource.xml",
	"classpath*:/mq/mq*.xml",
	"classpath*:/mq/applicationContext*.xml",
	"classpath*:/ws/applicationContext*.xml",
	"classpath*:/interceptor/applicationContext*.xml",
	}) 
public class CoverageBase extends SoapUIBase
{
 
	@Autowired
	public GenericApplicationContext applicationContext;
	
}

对象转类;
被xml转的对象要对class加注解@XmlRootElement--javax.xml.bind.annotation.XmlRootElement
package test.com.coverage;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class SoapUIBase
{
	public Logger log = Logger.getLogger(SoapUIBase.class);
	
	protected static final String HOST_PREFIX="http://127.0.0.1:8080";
	//protected static final String HOST_PREFIX="http://192.168.0.184:8080"; //Dev环境
	/**
	 * 
	 * 
	 * @param classPathFile soapUI的XML文件
	 * @param param 替换参数用的Map
	 * @return
	 * @throws Exception
	 */
	private SOAPMessage convertString2SOAP(String classPathFile,Map<String,String> param)  throws Exception
	{
		String prefix="${";
		String suffix="}";
		
		InputStream input=SoapUIBase.class.getResourceAsStream(classPathFile);
		if(input==null)
		{
			log.error("========error====="+classPathFile+" 找不到");
			throw new FileNotFoundException(classPathFile+"找不到");
		}
		
		BufferedReader reader=new BufferedReader(new InputStreamReader(input));
			
		String line;
		StringBuffer soapBuffer=new StringBuffer();
		
			while((line=reader.readLine())!=null)
			{
				if(param!=null && line.contains(prefix) ) 
				{
					String key=line.substring(line.indexOf(prefix)+prefix.length(), line.indexOf(suffix));
					if(param.get(key)!=null)
					{
						line=line.replace( prefix+key+suffix  , param.get(key));
					}else
					{
						log.error("========error=====文件classPathFile中的变量   "+key+"  未配置");
						throw new Exception("文件classPathFile中的变量   "+key+"  未配置");
					}
					
				}
				soapBuffer.append(line).append("\n");
			}
		
		 SOAPMessage reqMsg = MessageFactory.newInstance().createMessage(new MimeHeaders(), new ByteArrayInputStream(soapBuffer.toString().getBytes(Charset.forName("UTF-8"))));
         reqMsg.saveChanges();
         //log.info(classPathFile+"解析后的请求内容为----------\n"+soapBuffer);
         //reqMsg.writeTo(System.out);
         return reqMsg;
	}
	
	private String convertSOAP2String(SOAPMessage msg) throws Exception
	{
		Document doc = msg.getSOAPPart().getEnvelope().getOwnerDocument();
		StringWriter output = new StringWriter();
		Transformer   transformer=TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
		transformer.transform(new DOMSource(doc), new StreamResult(output));
		log.info("---------响应 \n"+output.toString());
		return output.toString();
	}
	
	protected String invokeWebService(String soapUIFile,String serviceURL,Map<String,String> param) throws Exception 
	{ 
		initLog4j();
		
		SOAPMessage reqMsg =convertString2SOAP(soapUIFile,param);
		SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage responseMsg = connection.call(reqMsg, serviceURL);
		String res=convertSOAP2String(responseMsg);
		return res;
	}
	/**
	 * 
	 * 
	 * @param classPathFile soapUi文件地址
	 * @param param 转换参数Map
	 * @param type 目标对象类型
	 * @return
	 * @throws Exception
	 */
	protected  <T> T parseRequest(String classPathFile,Map<String,String> param,Class<T> type) throws Exception 
	{ 
		initLog4j();
		
		SOAPMessage  soap=this.convertString2SOAP(classPathFile, param);
		SOAPBody body=soap.getSOAPBody();
		Element wrongParam=(Element)body.getElementsByTagName("arg0").item(0);
		
		Document doc=wrongParam.getOwnerDocument();
		String simpleName=type.getSimpleName();//大写
		String lowerName=simpleName.substring(0, 1).toLowerCase()+simpleName.substring(1, simpleName.length());
		Element paramName=doc.createElement(lowerName);
		NodeList list=wrongParam.getChildNodes();
		for(int i=0;i<list.getLength();i++)
		{
			paramName.appendChild(list.item(i).cloneNode(true) );
		}
		
		StringWriter output = new StringWriter();
		Transformer   transformer=TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
		transformer.transform(new DOMSource(paramName), new StreamResult(output));
		log.info(classPathFile+"---------解析的  [请求] 对象参数  \n"+output.toString());
		 
		JAXBContext context=JAXBContext.newInstance(type);  
		Unmarshaller unmarshaller=context.createUnmarshaller();
		
		T req=(T) unmarshaller.unmarshal(new StringReader(output.toString()));
		return req ;
	}
	private void initLog4j()
	{
		System.setProperty("log_home","c:/log");
		URL url=SoapUIBase.class.getResource("/log4j.xml");
		DOMConfigurator.configure(url);
	}
}

POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com</groupId>
		<artifactId>tcoreptms</artifactId>
		<version>1.0.0-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<groupId>com.test</groupId>
	<artifactId>tcoreptms-test</artifactId>
	<packaging>jar</packaging>
	<name>test Desc</name>

	<dependencies>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.easymock</groupId>
		    <artifactId>easymock</artifactId>
		    <version>3.2</version>
	    </dependency>
		 <dependency>
			<groupId>com..biz</groupId>
			<artifactId>tcoreptms-biz</artifactId>
		</dependency>
		 
	</dependencies>
<build>

	 <plugins>
     	 <!-- <plugin>
 				<groupId>org.jacoco</groupId>
				<artifactId>jacoco-maven-plugin</artifactId>
				<configuration>
					<destFile>${sonar.jacoco.itReportPath}</destFile>
				</configuration>
				<executions>
					<execution>
						<id>post-test</id>
						<configuration>
							<skip>true</skip>
						</configuration>
					</execution>
				</executions>
			</plugin> -->
      
    </plugins>
	</build>

</project>

你可能感兴趣的:(JUnit)