NSubstitute

NUnitのモックを使いこなせるようになってみようと思ってやってみた。 NUnit.mocks.DynamicMock を使ったら、警告が出た。

警告 1 'NUnit.Mocks.DynamicMock' は古い形式です: 'NUnit now uses NSubstitute'

 

というわけで、NSubstituteを使ってみた。

 

 

 

公式サイト(GitHub

http://nsubstitute.github.io/

 

公式サイト(nuget)

http://www.nuget.org/packages/NSubstitute

 

NUGet以外のインストール方法

  1. DLLをダウンロードする。 上記の公式サイト(github)にある「Download」でDLLが入ったzipファイルを取得できる。
  2. 解凍して、NSubstitute.dll をテストプロジェクトに置く。
  3. 参照設定に追加する。
  4. using NSubstitute; を追加する。

基本的な使い方

http://nsubstitute.github.io/help/getting-started/

  1. モックオブジェクトを作る。
  2. モックオブジェクトに、どう呼び出したらどう振舞うかを設定する。
  3. 使う。

public interface ICalculator
{
int Add(int a, int b);
string Mode { get; set; }
event EventHandler PoweringUp;
}
calculator.Add(1, 2).Returns(3);
Assert.That(calculator.Add(1, 2), Is.EqualTo(3));  => モックの挙動をテストしてみた。

 

その他の使い方

 このドキュメントに全部書いてある。

 http://nsubstitute.github.io/help.html

//Check a call was received/ not received.
calculator.Add(1, 2);
calculator.Received().Add(1, 2);  => アサーション成功
calculator.DidNotReceive().Add(5, 7);  => アサーション失敗

 

メモ モックとスタブの違い

このサイトでズバリ、分かりやすい。感謝です。

http://tocsworld.wordpress.com/2014/03/11/%E3%83%A2%E3%83%83%E3%82%AFmock%E3%81%A8%E3%82%B9%E3%82%BF%E3%83%96stub%E3%81%AE%E9%81%95%E3%81%84/