代码改变世界

Mock工具笔记

2008-12-14 15:14  敏捷的水  阅读(1663)  评论(0编辑  收藏  举报

1.准备被测试的类

Product 类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace TestTypeMock

{

    public class Product

    {

        public string Name { get; set; }

        public long ProductId { get; set; }

        public decimal Price { get; set; }

        public int CategoryId { get; set; }

 

        public decimal Discount(decimal discountPercent)

        {

            return this.Price * discountPercent;

        }

 

        public static long MarkUp(int times)

        {

            return 50 * times;

        }

 

        private long Add(int a, int b)

        {

            return a + b;

        }

 

        public long GetAddResult(int a, int b)

        {

            return Add(a, b);

        }

 

        public long LiveObjectAdd(int a, int b)

        {

            return GetAddLiveObject(a, b);

        }

 

        private long GetAddLiveObject(int a, int b)

        {

        throw new NotImplementedException("Not Implemented");

        }

    }

}

 

ShopCart类

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace TestTypeMock

    7 {

    8    public   class ShopCart

    9     {

   10        public decimal SumPrice(List<Product> allProduct)

   11        {

   12            decimal totalPrice = 0;

   13            foreach (Product item in allProduct)

   14            {

   15                totalPrice += Product.MarkUp(2);  // in order to mock static method

   16            }

   17            return totalPrice;

   18        }

   19 

   20        public decimal NatureAdd(Product p)

   21        {

   22            return p.Discount(5);

   23        }

   24     }

   25 }

 

Icalc类

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace TestTypeMock

    7 {

    8     public interface ICalc

    9     {

   10         long Add(int a, int b);

   11     }

   12 }

 

Duck类

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace TestTypeMock

    7 {

    8   public    class Duck

    9     {

   10       public bool CanSwim()

   11       {

   12           return true;

   13       }

   14 

   15     }

   16 }

 

Chicken 类

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 

    6 namespace TestTypeMock

    7 {

    8   public    class Chicken

    9     {

   10       public bool CanSwim()

   11       {

   12           return false;

   13       }

   14     }

   15 }

 

测试

1. AAA

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.VisualStudio.TestTools.UnitTesting;

    6 using TypeMock;

    7 using TypeMock.ArrangeActAssert;

    8 using TestTypeMock;

    9 namespace ProductTest

   10 {

   11     [TestClass]

   12     public class TestProduct

   13     {

   14 

   15         [TestInitialize]

   16         public void Setup()

   17         {

   18 

   19         }

   20 

   21         [TestMethod]

   22         public void ProductTest()

   23         {

   24             // Arrange

   25             Product fakeProduct = Isolate.Fake.Instance<Product>();

   26             Isolate.WhenCalled(() => fakeProduct.Discount(50)).WillReturn(60);

   27 

   28 

   29             // Act

   30             decimal discountPrice = fakeProduct.Discount(50);

   31 

   32             // Assert

   33             Assert.AreEqual(discountPrice, 60);

   34             Isolate.Verify.WasCalledWithAnyArguments(() => fakeProduct.Discount(70));

   35         }

   36 

   37         [TestMethod]

   38         public void TestCallOrginalMethod()

   39         {

   40             // Arrange

   41             Product fakeProduct = Isolate.Fake.Instance<Product>();

   42 

   43             // fakeProduct.Price = 200; // why can't use this way?

   44             Isolate.WhenCalled(() => fakeProduct.Price).WillReturn(200);

   45             Isolate.WhenCalled(() => fakeProduct.Discount((decimal)0.5)).CallOriginal();

   46 

   47             // Act

   48             decimal discountPrice = fakeProduct.Discount((decimal)0.5);

   49 

   50             // Assert

   51             Assert.AreEqual(discountPrice, 100);

   52             Isolate.Verify.WasCalledWithAnyArguments(() => fakeProduct.Discount(100));

   53             Isolate.Verify.WasCalledWithAnyArguments(() => fakeProduct.Price);

   54         }

   55 

   56         [TestMethod]

   57         [Description("Test Mock Static Method")]

   58         public void TestMockStaticMethod()

   59         {

   60             // Arrange

   61             Isolate.Fake.StaticMethods<Product>(Members.CallOriginal);

   62 

   63             Isolate.WhenCalled<long>(() => Product.MarkUp(5));

   64 

   65             // Act

   66             long newProductPrice = Product.MarkUp(5);

   67 

   68             // Assert

   69             Assert.AreEqual(newProductPrice, 250);

   70             Isolate.Verify.WasCalledWithAnyArguments(() => Product.MarkUp(5));

   71         }

   72 

   73         [TestMethod]

   74         public void TestMockStaticMethod2()

   75         {

   76             // Arrange

   77             Product fakeProduct = Isolate.Fake.Instance<Product>();

   78             Isolate.Fake.StaticMethods<Product>();

   79             Isolate.WhenCalled<long>(() => Product.MarkUp(2)).WillReturn(10);

   80 

   81             ShopCart s = new ShopCart();

   82             List<Product> list = new List<Product> { fakeProduct, fakeProduct, fakeProduct };

   83 

   84             // Act

   85             decimal b = s.SumPrice(list);  // will use  mock static method

   86 

   87             // Assert

   88             Assert.AreEqual(b, 30);

   89 

   90         }

   91 

   92         [TestMethod]

   93         [Isolated]

   94         [Description("Mock private method of class")]

   95         public void MockPrivate()

   96         {

   97             // Arrange

   98             Product mockProduct = Isolate.Fake.Instance<Product>();

   99             Isolate.NonPublic.WhenCalled(mockProduct, "Add").CallOriginal();

  100             Isolate.WhenCalled(() => mockProduct.GetAddResult(5, 5)).CallOriginal();

  101             // Act

  102             long result = mockProduct.GetAddResult(5, 5);

  103 

  104             //Assert

  105             Assert.AreEqual(10, result);

  106             Isolate.Verify.NonPublic.WasCalled(mockProduct, "Add").WithArguments(5, 5);

  107 

  108         }

  109 

  110         [TestMethod]

  111         public void TestLiveObject()

  112         {

  113             Product p = new Product();   // please notice this statement, not mocked object

  114             long result = p.GetAddResult(3, 5);

  115             Assert.AreEqual(8, result);

  116 

  117             // Arrange

  118             Isolate.NonPublic.WhenCalled (p, "GetAddLiveObject").WillReturn((long)10);

  119 

  120             // Act

  121             Assert.AreEqual(10,p.LiveObjectAdd(5, 5));

  122 

  123             // Assert

  124             Isolate.Verify.NonPublic.WasCalled(p, "GetAddLiveObject").WithArguments(5, 5);

  125 

  126         }

  127     }

  128 }

2. Nature Mock

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.VisualStudio.TestTools.UnitTesting;

    6 using TypeMock;

    7 using TypeMock.ArrangeActAssert;

    8 using TestTypeMock;

    9 using System.Text.RegularExpressions;

   10 

   11 namespace ProductTest

   12 {

   13     [TestClass]

   14     public class TestNatureMock

   15     {

   16         [TestMethod]

   17         [VerifyMocks]

   18         public void TestByNatureMock()

   19         {

   20             Product p = new Product();

   21             p.Price = 20;

   22             using (RecordExpectations record = RecorderManager.StartRecording())

   23             {

   24                 p.Discount(6);

   25                 record.Return((decimal)20);

   26                 record.CheckArguments(Check.IsEqual((decimal)5));

   27                 record.Repeat(2);            //前两次调用使用Mock的方法,后面使用自己的

   28                 record.VerifyMode = VerifyMode.Normal;

   29                 //    record.DefaultBehavior.Strict = StrictFlags.InstanceMethods;

   30 

   31             }

   32 

   33             ShopCart s = new ShopCart();

   34             Assert.AreEqual(s.NatureAdd(p), 20);   // use mocked statement

   35             Assert.AreEqual(s.NatureAdd(p), 20);  // use mocked statement

   36             Assert.AreEqual(s.NatureAdd(p), 100);  // use original statement

   37 

   38             // MockManager.Verify();  //use this or put [verifymodes] on method

   39         }

   40 

   41 

   42         [TestMethod]

   43         public void TestByImpictUse()

   44         {

   45             MockManager.Init();

   46 

   47             // Product is now being mocked

   48             Mock p = MockManager.Mock(typeof(Product));

   49 

   50             // set up our expectations

   51             p.ExpectAndReturn("MarkUp", (long)25).When(Check.IsEqual(5));

   52 

   53             // Act

   54             Assert.AreEqual((long)25, Product.MarkUp(5));

   55 

   56             // Verify

   57             MockManager.Verify();

   58         }

   59 

   60         [TestMethod]

   61         public void NatureMockLiveObject()

   62         {

   63             Product p = new Product();

   64             p.Price = 200;

   65             using (RecordExpectations record = RecorderManager.StartRecording())

   66             {

   67                 p.Discount((decimal)10);

   68                 record.Return((decimal)20);

   69                 record.Repeat(2);

   70                 record.WhenArgumentsMatch(Check.IsEqual((decimal)10));

   71             }

   72 

   73             Assert.AreEqual(p.Discount((decimal)10), 20);

   74             Assert.AreEqual(p.Discount((decimal)10), 20);

   75             MockManager.Verify();

   76         }

   77 

   78         [TestMethod]

   79         public void NatureMockInterface()

   80         {

   81             ICalc mockICalc = (ICalc)RecorderManager.CreateMockedObject<ICalc>();

   82             using (RecordExpectations record = RecorderManager.StartRecording())

   83             {

   84                 mockICalc.Add(5, 5);

   85                 record.Return((long)10);

   86             }      

   87             Assert.AreEqual(mockICalc.Add(5, 5), (decimal)10);

   88             MockManager.Verify();

   89         }

   90     }

   91 

   92 

   93 }

 

Mock Swap

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.VisualStudio.TestTools.UnitTesting;

    6 using TypeMock;

    7 using TypeMock.ArrangeActAssert;

    8 using TestTypeMock;

    9 

   10 namespace ProductTest

   11 {

   12     [TestClass]

   13   public    class TestMockSwap

   14     {

   15         [TestMethod]

   16         public void TestSwap()

   17         {

   18             Duck duck = new Duck();

   19             Chicken chicken = new Chicken();

   20             Assert.AreEqual(duck.CanSwim(), true);

   21             Assert.AreEqual(chicken.CanSwim(),false);

   22 

   23             Isolate.Swap.CallsOn(chicken).WithCallsTo(duck);

   24             Assert.AreEqual(chicken.CanSwim(), true);  // because swaped

   25 

   26             Assert.AreEqual(duck.CanSwim(), true);

   27 

   28             // how to back to call itself? below cause wrong, dead loop

   29           //  Isolate.Swap.CallsOn(chicken).WithCallsTo(chicken); //call itself

   30             Assert.AreEqual(chicken.CanSwim(), true);

   31 

   32 

   33         }

   34     }

   35 }

 

Test Base Class

 

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.VisualStudio.TestTools.UnitTesting;

    6 using TypeMock;

    7 using TypeMock.ArrangeActAssert;

    8 using TestTypeMock;

    9 

   10 namespace ProductTest

   11 {

   12 

   13     [TestClass]

   14    public    class MockBaseClass

   15     {

   16         /// <summary>

   17         /// Mock base class method

   18         /// </summary>

   19         [TestMethod]

   20         public void TestBaseClass()

   21         {

   22             Mock mock = MockManager.Mock<Dog>();

   23             mock.CallBase.ExpectAndReturn("Do", "mock Animal Do");

   24 

   25             Dog dog = new Dog();

   26             Assert.AreEqual(dog.Do(), "mock Animal Do: I am Dog");

   27 

   28             MockManager.Verify();

   29 

   30         }

   31     }

   32 

   33    public class Animal

   34    {

   35        public virtual string Do()

   36        {

   37            return "Animal Do";

   38        }

   39    }

   40 

   41    public class Dog : Animal

   42    {

   43        public override string Do()

   44        {

   45            return base.Do() + ": I am Dog";

   46        }

   47    }

   48 }

 

Mock .net 3.5

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.VisualStudio.TestTools.UnitTesting;

    6 using TypeMock;

    7 using TypeMock.ArrangeActAssert;

    8 using TestTypeMock;

    9 namespace ProductTest

   10 {

   11 

   12     [TestClass]

   13     public class TypeMockNet35

   14     {

   15 

   16         [TestMethod]

   17         public void TestAutoProperty()

   18         {

   19             AutoProperty p = Isolate.Fake.Instance<AutoProperty>();

   20             Isolate.WhenCalled(() => p.Name).WillReturn("Jack");

   21             Isolate.Swap.NextInstance<AutoProperty>().With(p);

   22 

   23             AutoProperty p1 = new AutoProperty();

   24             p1.Name = "wang";

   25 

   26             Assert.AreEqual("Jack", p1.Name);

   27         }

   28     }

   29 

   30     public class AutoProperty

   31     {

   32         public string Name { get; set; }

   33     }

   34 }