下面我們就來介紹一下MoQ的具體用法:
一、基礎知識
在使用MoQ之前我們必須要先在測試程式中引入Moq.dll,使用MoQ的主要命名空間是Moq,其中最重的類就是Mock<T>,我們可以用這個類來模拟接口。
1、方法
public interface ITest
{
string Test();
}
測試代碼:
簡單測試代碼
2、比對參數
public interface IMatchTest
string Test(int test);
比對測試
上邊測試代碼模拟實作IMathTest接口執行個體,其中如果Test方法的參數是偶數,其傳回值為“偶數”。這裡的IT用來過濾參數的類,其具體解釋可以參見MoQ的文檔
3、屬性
public interface IPropertiesTest
int Test { get; set; }
var testProperties = new Mock<IPropertiesTest>();
testProperties.Setup(p => p.Test).Returns(1);
Assert.AreEqual(1, testProperties.Object.Test);
或者
var testProperties = new Mock<IPropertiesTest>();
testProperties.SetupProperty(p => p.Test,1);
4、Callback
當執行某方法時調用其内部輸入的Action委托
Callback
在調用Test方法是執行了count++
判斷某方法或屬性是否執行過
如果代碼如下:
Code
會抛出異常,因為第3行執行時Test方法還沒有被調用過,改為如下代碼可以通過測試
其他細節可以檢視MoQ文檔。
二、應用
先建立一個Account類:
建立一個資料庫Provider接口:
public interface ITransferProvider
void TransferTo(Account accountFrom, Account accountTo);
然後建立轉賬處理類:
TransferProcess
下邊我們來測試這個轉賬處理類:
三、參考
<a href="http://code.google.com/p/moq/wiki/QuickStart" target="_blank">http://code.google.com/p/moq/wiki/QuickStart</a>
<a href="http://www.codethinked.com/post/2009/03/08/Beginning-Mocking-With-Moq-3-Part-1.aspx" target="_blank">Beginning Mocking With Moq 3 – Part 1</a>
<a href="http://www.codethinked.com/post/2009/03/10/Beginning-Mocking-With-Moq-3-Part-2.aspx" target="_blank">Beginning Mocking With Moq 3 - Part 2</a>
<a href="http://www.codethinked.com/post/2009/03/13/Beginning-Mocking-With-Moq-3-Part-3.aspx" target="_blank">Beginning Mocking With Moq 3 - Part 3</a>
<a href="http://www.codethinked.com/post/2009/03/31/Beginning-Mocking-With-Moq-3-Part-4.aspx" target="_blank">Beginning Mocking With Moq 3 - Part 4</a>
本文轉自 你聽海是不是在笑 部落格園部落格,原文連結:http://www.cnblogs.com/nuaalfm/archive/2009/11/25/1610755.html ,如需轉載請自行聯系原作者