Moq basics: no basics for getting started with guitar
I. Concepts
Moq is a Mocking library designed and developed for · NET by leveraging features such as the Linq Expression Tree and Lambda expressions. Mock literally means simulating that the behavior of the simulated object has achieved the effect of deceiving the target (the object to be tested.
When the Moq simulation class type is used, the sealing class cannot be simulated, the static method cannot be simulated (the adapter can solve), and the simulated method and attributes must be modified by virtual.
Ii. Example
1 // object to be simulated 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 // target method 16 public decimal GetPriceWithTax (ITaxCalculate calc) 17 {18 return calc. getTax (RawPrice) + RawPrice; 19} 20} 21 22 // unit test 23 [TestMethod] 24 public void TestGetTax () 25 {26 Product product = new Product27 {28 Id = 1,29 Name = "TV", 30 RawPrice = 2520.m31}; 32 33 // create a Mock object, empty frame 34 Mock <ITaxCalculate> fakeTaxCalculator = new Mock <ITaxCalculate> (); 35 36 // simulate object behavior 37 fakeTaxCalculator. setup (tax => tax. getTax (25.0 M )). returns (5.0 M); 38 39 // call the target method 40 decimal calcTax = product. getPriceWithTax (fakeTaxCalculator. object); 41 42 // Assert 43. areEqual (calcTax, 30.0 M); 44}
Iii. Mock Method 4. Reference Links
- Http://blog.csdn.net/alicehyxx/article/details/50667307
- Http://www.cnblogs.com/wintersun/archive/2010/09/04/1818092.html