NUnitのPropertyConstraintの使いどころ(^o^)
まずは、以下のコードを見て欲しい。
using System; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; namespace LearningNUnit.Tests.ConstraintModel { [TestFixture] public class PropertyConstraintTest { private class Customer { private string name_; private Customer(string name) { this.name_ = name; } public static Customer CreateStubCustomer() { return new Customer("tsune"); } public string Name { get { return name_; } } } [Test] public void プロパティ存在制約が成功すべき() { Assert.That(Customer.CreateStubCustomer(), Has.Property("Name")); } [Test] [ExpectedException(typeof(NullReferenceException))] public void プロパティ存在制約が失敗すべき() { Assert.That(Customer.CreateStubCustomer(), Has.Property("Address")); } [Test] public void プロパティの戻り値取得の制約が成功すべき() { Assert.That(Customer.CreateStubCustomer(), Has.Property("Name", "tsune")); } [Test] [ExpectedException(typeof(AssertionException))] public void プロパティの戻り値取得の制約が失敗すべき() { Assert.That(Customer.CreateStubCustomer(), Has.Property("Name", "hoge")); } } }
鋭い方ならお気づきだろうが、PropertyConstraintを使うことによってエンティティのようなクラスのテストを書く場合に、クラスだけ作成しておけば、後はいちいちコンパイルエラーを気にすることなく、一気にテストが書ける。
また、プロパティの戻り値のチェックまで1行で書けてしまうのも嬉しい。