Gallio/MbUnit有一个contract verifier这正是你正在寻找。的AccessContract的典型用法如下:
public class Foo // Dummy reference type.
{
private readonly int value;
public int Value { get { return value; } }
public Foo (int value)
{
this.value = value;
}
}
public class Bar
{
private Foo foo;
public Bar(string unusedParameter) { }
public Foo Foo // A complex property to be tested!
{
get { return foo; }
set
{
if (value == null)
throw new ArgumentNullException("value");
if (value.Value < 0)
throw new ArgumentOutOfRangeException();
if (value.Value == 666)
throw new ArgumentException("Inferno value strictly forbidden.");
foo = value;
}
}
}
和使用AccessorContract运行对房地产各种测试的测试夹具。
[TestFixture]
public class BarTest
{
[VerifyContract]
public readonly IContract AccessorTests = new AccessorContract<Bar, Foo>
{
Getter = target => target.Foo,
Setter = (target, value) => target.Foo = value,
ValidValues = { new Foo(123), new Foo(456), new Foo(789) },
AcceptNullValue = false,
DefaultInstance =() => new Bar("Hello"),
InvalidValues =
{
{ typeof(ArgumentOutOfRangeException), new Foo(-123), new Foo(-456) },
{ typeof(ArgumentException), new Foo(666) }
}
};
}
合同验证生成以下的单元测试:
看一看的MbUnit test project更多应用实例。
你检查过pex和痣吗? - http://research.microsoft.com/en-us/projects/pex/ – luketorjussen
@Luke我曾与PEX玩过,但还没有时间彻底使用它 –
不会间接测试它们的测试吗?属性作为其执行的一部分,捕捉这些错误?你真的需要更多的测试吗? – Gishu