Monday, February 29, 2016

NSubstibute and Moq Comparison


(1) Mock<T>.Object is need to get T, while Substitute<T>.For is T
 (2) Mock function calls "Faking" go through SetUp(Func).Returns, while NSubstiture only need .Returns
 (3) The actual calls are the same
 (4) Mock has VerifyAll(), NSubstibute does not.

    [TestClass]
     public class UnitTest1
     {
         IListing listing = Substitute.For<IListing>();
         IMarketDepthDataService depthDataService = Substitute.For<IMarketDepthDataService>();

        Mock<IListing> listing2 = new Mock<IListing>();
         private Mock<IMarketDepthDataService> depthDataService2 = new Mock<IMarketDepthDataService>();

        [TestInitialize ]
         public void Init()
         {
             depthDataService.GetDepthForListing(listing, 5).Returns(i => new ListingMarketDepthData(listing, 5));
             depthDataService2.Setup(i => i.GetDepthForListing(listing2.Object, 5)).Returns(new ListingMarketDepthData(listing2.Object, 5));
         }

        [TestCleanup]
         public void Cleanup()  // have to be Public to get called
         {
            
         }

        [TestMethod]
         public void TestMethod1()
         {
             var data = depthDataService.GetDepthForListing(listing, 5);

            var data2 = depthDataService2.Object.GetDepthForListing(listing2.Object, 5);

            Assert.IsTrue(data2.Summary == "3_Year,Depth=10" && data.Summary == "3_Year,Depth=10");

            depthDataService2.VerifyAll();
         }
     }

    public interface IListing
     {
         string Name { get; set; }
     }

    public interface IMarketDepthDataService
     {
         ListingMarketDepthData GetDepthForListing(IListing listing, int level);
     }

    public class ListingMarketDepthData
     {
         public ListingMarketDepthData(IListing listing, int maxDepth)
         {
             Summary = "3_Year,Depth=10";
         }

        public string Summary { get; set; }
     }


No comments:

Post a Comment