我使用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