NSubstitute 其它用法
前篇文章已簡單介紹 NSubstitute 的用法,其實這個 library 還有其它實用的功能,以下一一列舉:
建構子呼叫
NSubstitute 可以直接使用類別,可以自然也可以呼叫其建構子,程式碼如下:
public class FooClass
{
public FooClass(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
public int TenX()
{
return X * 10;
}
public virtual int FooMethod(int x)
{
return x;
}
}
private static void Example()
{
// constructor example
FooClass foo = Substitute.For<FooClass>(1, 2);
foo.FooMethod(default).Returns(900);
Console.WriteLine($"foo.X: {foo.X}");
Console.WriteLine(foo.FooMethod(8));
}
從程式碼中可以看到 FooClass 需要兩個參數,NSubstitute 可以直接呼叫,而重新設定 FooMethod 的回傳值時,參數可用 default
來代替,需注意的是,FooMethod 是被宣告為 virtual 的。
檢查 method 是否被呼叫
想想一個情境,你設計的 library 中某個 API 決定要移掉,然後希望使用者不要再使用,這時可透過 NSubstitute 來檢查:
service.DoSomeThing();
service.ClearReceivedCalls();
service.Received().DoSomeThing(); //if doesn't call DoSomeThing, then get exception
service.DidNotReceive().DoSomeThing();
ClearReceivedCalls
是將之前有呼叫過的記錄都清掉,重新來過。service.Received().DoSomeThing();
這一行就是檢查 method 是否有被呼叫,當然,前面提的是不希望被呼叫,那就是使用 DidNotReceive()
。
Callback
Callback 可以在 Method 被呼叫時做些額外的邏輯或是做 log,範例如下:
int count = 0;
service.GetIntValue().Returns(8).AndDoes(x => count++);
service.When(x => x.DoSomeThing()).Do(x => count++);
service.GetIntValue();
service.DoSomeThing();
用法有兩種,呼叫 AddDoes
或是用 When...Do
,我個人偏好 AndDoes
,因為用起來較簡單。
參考資料