我使用Lokad Shared Library來定義業務驗證規則。以下是我測試的情況(從開源樣品):
[Test]
public void Test()
{
ShouldPass("[email protected]", "pwd", "http://ws.lokad.com/TimeSerieS2.asmx");
ShouldPass("[email protected]", "pwd", "http://127.0.0.1/TimeSerieS2.asmx");
ShouldPass("[email protected]", "pwd", "http://sandbox-ws.lokad.com/TimeSerieS2.asmx");
ShouldFail("invalid", "pwd", "http://ws.lokad.com/TimeSerieS.asmx");
ShouldFail("[email protected]", "pwd", "http://identity-theift.com/TimeSerieS2.asmx");
}
static void ShouldFail(string username, string pwd, string url)
{
try
{
ShouldPass(username, pwd, url);
Assert.Fail("Expected {0}", typeof (RuleException).Name);
}
catch (RuleException)
{
}
}
static void ShouldPass(string username, string pwd, string url)
{
var connection = new ServiceConnection(username, pwd, new Uri(url));
Enforce.That(connection, ApiRules.ValidConnection);
}
凡ValidConnection規則定義爲:如果某些失敗的情況下被發現
public static void ValidConnection(ServiceConnection connection, IScope scope)
{
scope.Validate(connection.Username, "UserName", StringIs.Limited(6, 256), StringIs.ValidEmail);
scope.Validate(connection.Password, "Password", StringIs.Limited(1, 256));
scope.Validate(connection.Endpoint, "Endpoint", Endpoint);
}
static void Endpoint(Uri obj, IScope scope)
{
var local = obj.LocalPath.ToLowerInvariant();
if (local == "/timeseries.asmx")
{
scope.Error("Please, use TimeSeries2.asmx");
}
else if (local != "/timeseries2.asmx")
{
scope.Error("Unsupported local address '{0}'", local);
}
if (!obj.IsLoopback)
{
var host = obj.Host.ToLowerInvariant();
if ((host != "ws.lokad.com") && (host != "sandbox-ws.lokad.com"))
scope.Error("Unknown host '{0}'", host);
}
(即:新的有效連接網址添加),然後規則和測試得到更新。
有關此模式的更多信息,請參閱this article。一切都是開源的,所以請隨時重複使用或提出問題。
PS:注意,在這種樣品複合規則中使用原始規則(即StringIs.ValidEmail或StringIs.Limited)充分自行測試並因而不需要過度的單元測試。
我重新說了一下我的問題 - 請再讀一遍 – JacobE 2009-01-08 15:06:46