NSubstitute - 檢查方法被執行幾次或沒有執行
範例程式碼放在 GitHub
前言
當遇到沒有回傳值得時候,就可以透過執行幾次該方法去驗證 或是 比較複雜的流程
應該要重複執行方法時也可以用檢查執行幾次的方式驗證
Received的設定
直接看程式碼
public interface ICalculator
{
void Clear(int level);
}
public class MyDemo
{
private readonly ICalculator _calculator;
public MyDemo(ICalculator calculator)
{
this._calculator = calculator;
}
public void Action1(bool clearFlag)
{
if (clearFlag == true)
{
this._calculator.Clear(7);
}
}
}
[TestMethod]
public void test1()
{
//arrange
//NSubstitute會產生一個ICalculator 假的實體出來
ICalculator calculator = Substitute.For<ICalculator>();
var myDemo = new MyDemo(calculator);
//act
myDemo.Action1(true);
//assert
calculator.Received(1).Clear(7);
calculator.DidNotReceive().Clear(1);
calculator.Received(1).Clear(Arg.Any<int>());
calculator.ReceivedWithAnyArgs(1).Clear(default(int));
}
[TestMethod]
public void test2()
{
//arrange
//NSubstitute會產生一個ICalculator 假的實體出來
ICalculator calculator = Substitute.For<ICalculator>();
var myDemo = new MyDemo(calculator);
//act
myDemo.Action1(false);
//assert
calculator.DidNotReceive().Clear(0);
calculator.DidNotReceive().Clear(Arg.Any<int>());
calculator.DidNotReceiveWithAnyArgs().Clear(default(int));
}
這邊用到的觀念跟之前都一樣要驗證方法被執行次數與參數要指定時就是用
calculator.Received(1).Clear(7);
如果會執行到兩次的話就是Received(2)
不要管參數的時候 還是可以用 Arg.Any
或 ReceivedWithAnyArgs
如果不應該被執行就是用 DidNotReceive
也就是Received(0)
建議大家用 DidNotReceive
這樣閱讀起來比較直覺
viod 的方法就用
Received DidNotReceive
做驗證囉結語
接下來介紹ref 或 out 的用參數當回傳值該如何處理
如果內容有誤請多鞭策謝謝