開發 Web 服務時,反覆部署到 Tomcat 等容器進行測試既耗時又繁瑣。XFire 提供了一種優雅的解決方案:通過繼承 AbstractXFireSpringTest 抽象類,開發者可以直接在單元測試環境中啟動服務,結合 JUnit 實現快速驗證,極大提升了開發效率。
AbstractXFireSpringTest 繼承自 AbstractXFireTest,後者又是 TestCase 的子類,這意味著你可以直接使用 JUnit 的所有斷言與生命週期管理功能。測試類只需實現 createContext() 方法以提供 Spring 應用上下文,即可獲得完整的 XFire 運行環境。
package com.kuaff.xfire.samples;
import java.net.URL;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.service.Endpoint;
import org.codehaus.xfire.spring.AbstractXFireSpringTest;
import org.jdom.Document;
import org.springframework.context.ApplicationContext;
public class MathClientTest extends AbstractXFireSpringTest {
public void testService() throws Exception {
Document wsdl = getWSDLDocument("MathService");
printNode(wsdl);
}
protected ApplicationContext createContext() {
return new ClassPathXmlApplicationContext(new String[] {
"/org/codehaus/xfire/spring/xfire.xml",
"/META-INF/xfire/services.xml"
});
}
}
關鍵點在於 createContext() 方法:它載入 XFire 核心配置與服務定義文件,構建出一個獨立的 Spring 容器。測試方法中調用 getWSDLDocument() 即可獲取指定服務的 WSDL 文檔,驗證服務發布是否正常。
除了驗證 WSDL,更常見的需求是實際調用服務並檢查返回結果。XFire 提供了 invokeService() 方法配合 XPath 斷言:
Document response = invokeService("MathService", "Add.xml");
addNamespace("k", "https://www.kuaff.com/xfire/mathservice");
assertValid("//soap:Body/k:addResponse", response);
printNode(response);
assertValid() 方法接受 XPath 表達式,能精準驗證 SOAP 響應中特定節點的存在與內容,實現了契約式測試。
SpringSide 專案展示了更完整的測試模式:
package org.springside.bookstore.service;
public class XFireTest extends AbstractXFireSpringTest {
protected final Log log = LogFactory.getLog(getClass());
public void setUp() throws Exception {
super.setUp();
}
public void testGetWsdl() throws Exception {
Document doc = getWSDLDocument("BookService");
assertValid("//xsd:complexType[@name=\"Book\"]", doc);
assertValid("//xsd:complexType[@name=\"Category\"]", doc);
}
protected ApplicationContext createContext() {
return new ClassPathXmlApplicationContext(new String[]{"classpath*:applicationContext*.xml"});
}
}
此處使用通配符載入所有應用上下文文件,並在 setUp() 中調用父類初始化,確保測試環境就緒。測試方法通過 XPath 驗證 WSDL 中包含預期的複雜類型定義,確保契約穩定。
掌握這套機制,讓 Web 服務測試從「部署驗證」轉變為「代碼即測試」,是提升 XFire 開發效率的關鍵一步。