我有一个webservice (运行在jBoss 7.4中),它使用MTOM接收文件。
客户端(另一个应用程序)。(用于测试的SoapUI )发送文件,然后我们接收它。
创建一个带有附加文件的请求的测试的最佳方法是什么,然后检查附件是否真的收到了(比较二进制数据)。
我该怎么做?
发布于 2015-02-05 12:35:18
几天前,我为我的应用程序编写了一个类似的测试用例。是的,它比较了实际内容。下面是源代码。这可能会对你有帮助。
/**
* Compares the contents of SOAP attachment and contents of actual file used for creating the attachment
* Useful for XML/HTML/Plain text attachments
* @throws SOAPException
* @throws IOException
* @throws IllegalArgumentException
* @throws ClassNotFoundException
*/
@Test
public void testSetAndGetContentForTextualAttachment() throws SOAPException, IOException,
IllegalArgumentException, ClassNotFoundException {
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
SOAPMTOMMessageImpl soapImpl = new SOAPMTOMMessageImpl(soapMessage);
SOAPPart part = soapMessage.getSOAPPart();
SOAPEnvelope envelope = part.getEnvelope();
SOAPBody body = envelope.getBody();
SOAPBodyElement element = body.addBodyElement(envelope.createName(
"test", "test", "http://namespace.com/"));
// Create an Attachment from a file
File attachmentFile = new File ("C:\\temp\\temp.txt");
// get the expected contents from a file
StringBuffer expectedContent = new StringBuffer();
String line = null;
BufferedReader br = new BufferedReader(new FileReader(attachmentFile));
while((line = br.readLine()) != null){
expectedContent = expectedContent.append(line);
}
// create attachment
// Uses my application's custom classes, but you can use normal SAAJ classes for doing the same.
Attachment fileAttachment = soapImpl.createAttachmentFromFile(attachmentFile, "text/plain");
// content id will be used for downloading the attachment
fileAttachment.setContentID(attachmentFile.getName()+".restore");
// create MTOM type soap object from this attachment
QName fileSoapAttachmentQname = new QName("http://namespace.com/", "AttachFileAsSOAPAttachmentMTOM", "AttachmentElement");
soapImpl.setXopQname(fileSoapAttachmentQname);
soapImpl.addAttachmentAsMTOM(fileAttachment, element);
// Extract the attachment and cross check the contents
StringBuffer actualContent = new StringBuffer();
List<Attachment> attachments = soapImpl.getAllAttachments();
for(int i=0; i<attachments.size(); i++){
AttachmentPart attachmentPart = ((AttachmentImpl) attachments.get(i)).getAttachmentPart();
BufferedInputStream bis = new BufferedInputStream (attachmentPart.getDataHandler().getInputStream());
byte[] data = new byte[1024];
int numOfBytesRead = 0;
while(bis.available() > 0){
numOfBytesRead = bis.read(data);
String tmp = new String(data,0,numOfBytesRead);
actualContent = actualContent.append(tmp);
}
bis.close();
}
try {
Assert.assertEquals(true,
(expectedContent.toString()).equals(actualContent.toString()));
} catch (Throwable e) {
collector.addError(e);
}}
若要在服务器端进行类似的验证,可以使用内容长度标题值进行比较。或者,您可以添加一个额外的属性来确定预期的附件大小或检查和的种类。
_Thanks,布什汉
https://stackoverflow.com/questions/27796160
复制相似问题