Moq是利用諸如Linq表達式樹和Lambda表達式等·NET 3.5的特性,為·NET設計和開發的Mocking庫。Mock字面意思即模擬,模擬對象的行為已達到欺騙目標(待測試對象)的效果.
Moq模擬類類型時,不可模擬密封類,不可模擬靜態方法(適配器可解決),被模擬的方法及屬性必須被virtual修飾.
1 //待模擬對象
2 public interface ITaxCalculate
3 {
4 decimal GetTax(decimal rawPrice);
5 }
6
7 public class Product
8 {
9 public int Id { get; set; }
10
11 public string Name { get; set; }
12
13 public decimal RawPrice { get; set; }
14
15 //目標方法
16 public decimal GetPriceWithTax(ITaxCalculate calc)
17 {
18 return calc.GetTax(RawPrice) + RawPrice;
19 }
20 }
21
22 //單元測試
23 [TestMethod]
24 public void TestGetTax()
25 {
26 Product product = new Product
27 {
28 Id = 1,
29 Name = "TV",
30 RawPrice = 25.0M
31 };
32
33 //創建Mock對象,反射構建模擬對象空框架
34 Mock<ITaxCalculate> fakeTaxCalculator = new Mock<ITaxCalculate>();
35
36 //模擬對象行為
37 fakeTaxCalculator.Setup(tax => tax.GetTax(25.0M)).Returns(5.0M);
38
39 //調用目標方法
40 decimal calcTax = product.GetPriceWithTax(fakeTaxCalculator.Object);
41
42 //斷言
43 Assert.AreEqual(calcTax, 30.0M);
44 }