Thursday, 7 November 2013

Stub VS Shim VS Mock. Differences between Microsoft.Fake framework and Moq framework.

using System;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MicrosoftFakesFrameworkPlayClassLibrary;
using Moq;

namespace UnitTestProject
{
    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void TestUsingStub()
        {
            IStockFeed stockFeed =
                new MicrosoftFakesFrameworkPlayClassLibrary.Fakes.StubIStockFeed()
                {
                    GetSharePriceString = (company) => 7890
                };

            var actual = stockFeed.GetSharePrice("bbc");
        }

        [TestMethod]
        public void TestUsingShim()
        {
            using (ShimsContext.Create())
            {
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);

                var now = DateTime.Now;

                Assert.AreEqual(2000, now.Year);
            }
        }

        // To use Mock, you need to deal with Mock Wrap object. While as MS Fakes framework already generated 
        // Stub and Shim objects for you.
        [TestMethod]
        public void TestUsingMock()
        {
            var mock = new Mock();
            mock.Setup(instance => instance.GetSharePrice(It.IsAny())).Returns(1234);

            //Action
            var actual = mock.Object.GetSharePrice("myCompany");

            //Assert
            Assert.AreEqual(1234, actual);
        }
    }
}