NUnit に Spec っぽい書き方を提供する Should
社内では
NUnit が主流なのですが、やっぱり rspec みたいな should〜 って書き方は読みやすいなーと思うのです。Assert はそれはそれで見慣れているのですが。
NSpec や MSpec のような BDD フレームワークを使えばというのもあるのですが、QAという立場上開発が主で使うツールをとやかく言うのもアレなので、NUnit でも Spec っぽく書けるラッパーを書いたりしてたのですが、やはり先人はいました。
Should Assertion Library
このライブラリは NUnit を含む複数のテストライブラリに should のシンタックスを追加するものです。
インストール
ダウンロードして参照に加えるか、NuGetをインストールしていれば以下。
ShouldFluent は Should の fluent API 版です。
Install-Package Should Install-Package ShouldFluent
使い方
CoddPlex のサイトの方に詳細なサンプルがあるので、そちらを見てもらう方が早いですが、簡単に記述すると以下のようになります。
[TestFixture] public class ShouldSample { [TestCase] public void TestAssertIsTrue() { Assert.IsTrue(true); // NUnit の Assert } [TestCase] public void TestShouldBeTrue() { true.ShouldBeTrue(); // 同じものを Should で記述。 } [TestCase] public void TestShouldBeTrueFail() { false.ShouldBeTrue(); // もちろん失敗します。 } // Should で基本的なアサーションを記載 [TestCase] public void TestShouldAny() { var exist = "result"; var empty = ""; var stringEmpty = string.Empty; string nullValue = null; exist.ShouldNotBeEmpty(); exist.ShouldNotBeNull(); exist.ShouldBeSameAs(exist); exist.ShouldBeType<string>(); exist.ShouldContain("su"); exist.ShouldEqual("result"); empty.ShouldBeEmpty(); stringEmpty.ShouldBeEmpty(); nullValue.ShouldBeNull(); } // ShouldFluent で上記の Should の例を書きなおし [TestCase] public void TestShouldFluent() { var exist = "result"; var empty = ""; var stringEmpty = string.Empty; string nullValue = null; exist.Should().Not.Be.Empty(); exist.Should().Not.Be.Null(); exist.Should().Equals(exist); // exist.ShouldBeType<string>(); この例だけ ShouldFluent で書き直せない? exist.Should().Contain("su"); exist.Should().Equal("result"); empty.Should().Be.Empty(); stringEmpty.ShouldBeEmpty(); stringEmpty.Should().Be.Empty(); nullValue.Should().Be.Null(); } }
とまあ、NUnit でテストを書かれている方からすれば、シンタックスが違うだけで、何も変わらないと思います。本当にアサーションの部分だけ Spec ぽく書いているだけなので BDD っぽくも何もないですね。