我有一个使用MTOM接收文件的Web服务(在jBoss 7.4中运行)。
客户端(另一个应用程序。用于测试的 SoapUI)发送文件,我们会收到它。
创建测试的最佳方法是什么,该测试执行附加文件的请求,然后检查附件是否确实已收到(比较二进制数据)。
我应该怎么做?
几天
前我为我的应用程序编写了一个类似的测试用例。是的,它比较实际内容。下面是源代码。这可能对您有所帮助。
/**
* 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);
}
}
若要在服务器端进行类似的验证,可以使用内容长度标头值进行比较。或者,您可以添加额外的属性来确定预期的附件大小或校验和类型。
_谢谢布山