WCF 服務測試不僅是驗證功能正確性,更涉及傳輸協議、安全性、併發、效能等多維度。手動測試耗時、易錯、難回歸。本文示範建構自動化測試工具,實現持續整合就緒的測試管線。
[ServiceContract]
public interface ICryptoHashService
{
[OperationContract]
string GetCryptoHash(string input);
}
public class CryptoHashService : ICryptoHashService
{
public string GetCryptoHash(string input)
{
byte[] bytes = Encoding.Unicode.GetBytes(input);
using (var md5 = new MD5CryptoServiceProvider())
{
byte[] hash = md5.ComputeHash(bytes);
return BitConverter.ToString(hash); // 格式:E6-76-0D-55...
}
}
}
<system.serviceModel>
<services>
<service name="CryptoHashService" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="ICryptoHashService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
svcutil.exe https://localhost/WCF/CryptoHashService/Service.svc
// 產生 CryptoHashService.cs (Proxy代碼) 與 output.config (繫結配置)
public class TestCaseData
{
public string CaseId { get; }
public string Input { get; }
public string ExpectedHash { get; }
public TestCaseData(string id, string input, string expected)
{
CaseId = id; Input = input; ExpectedHash = expected;
}
}
var wsb = new WSHttpBinding
{
Name = "WSHttpBinding_ICryptoHashService",
CloseTimeout = TimeSpan.FromMinutes(1),
OpenTimeout = TimeSpan.FromMinutes(1),
ReceiveTimeout = TimeSpan.FromMinutes(10),
SendTimeout = TimeSpan.FromMinutes(1),
MaxReceivedMessageSize = 65536,
MessageEncoding = WSMessageEncoding.Text,
Security = { Mode = SecurityMode.Message }
};
var epa = new EndpointAddress("https://localhost/WCF/CryptoHashService/Service.svc");
var client = new CryptoHashServiceClient(wsb, epa);
var testCases = new List<TestCaseData>
{
new TestCaseData("001", "Hello world", "E6-76-0D-55-5C-32-F6-6F-5E-15-93-31-DB-20-FD-8E"),
new TestCaseData("002", "Goodbye world", "1A-05-3C-C0-4A-18-13-06-0E-AC-EA-BA-46-EC-CF-B1"),
new TestCaseData("003", "", "D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E")
};
foreach (var tc in testCases)
{
Console.WriteLine($"Case: {tc.CaseId} | Input: {tc.Input}");
string actual = client.GetCryptoHash(tc.Input);
bool passed = actual == tc.ExpectedHash;
Console.WriteLine($"Expected: {tc.ExpectedHash}");
Console.WriteLine($"Actual: {actual}");
Console.WriteLine(passed ? "* PASS *" : "** FAIL **");
Console.WriteLine();
}
將測試案例外部化至 XML/JSON/SQL,支援數千案例,分離測試邏輯與測試資料。
ConcurrencyMode 行為FaultContract、CommunicationException、TimeoutExceptionWCF 測試的關鍵在於:隔離測試層級(單元/整合/效能/安全)、自動化執行、資料驅動、CI 整合。本文示範的測試工具雖簡單,但包含 Proxy 產生、繫結程式化、案例驅動、結果報告等核心要素,可作為企業級測試框架的起點。