我正在测试包含逻辑的构造函数——例如验证或有条件地设置私有状态。验证错误最终会导致构造函数抛出异常。成功的执行最终会创建一个对象,该对象根据构造函数中设置的状态表现出特定的行为。
无论哪种方式,它都需要测试。但是构造函数测试很无聊,因为它们看起来都一样——调用构造函数,做出断言。测试方法声明通常比整个测试逻辑占用更多的空间......所以我写了一个简单的测试库来帮助为构造函数编写声明性测试:How to Easily Test Validation Logic in Constructors in C#
这是一个示例,我在一个类的构造函数上尝试了七个测试用例:
[TestMethod]
public void Constructor_FullTest()
{
IDrawingContext context = new Mock<IDrawingContext>().Object;
ConstructorTests<Frame>
.For(typeof(int), typeof(int), typeof(IDrawingContext))
.Fail(new object[] { -3, 5, context }, typeof(ArgumentException), "Negative length")
.Fail(new object[] { 0, 5, context }, typeof(ArgumentException), "Zero length")
.Fail(new object[] { 5, -3, context }, typeof(ArgumentException), "Negative width")
.Fail(new object[] { 5, 0, context }, typeof(ArgumentException), "Zero width")
.Fail(new object[] { 5, 5, null }, typeof(ArgumentNullException), "Null drawing context")
.Succeed(new object[] { 1, 1, context }, "Small positive length and width")
.Succeed(new object[] { 3, 4, context }, "Larger positive length and width")
.Assert();
}
通过这种方式,我可以为我的构造函数测试所有相关案例,而无需输入太多内容。