Wednesday, December 26, 2018

Quick Moq Reminder


Links



Code Sample


  

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/// 
/// https://daedtech.com/mock-of-and-mock-get-in-moq/
/// https://www.developerhandbook.com/unit-testing/writing-unit-tests-with-nunit-and-moq/
/// 
namespace MoqPractice
{
    public interface IPerson
    {
        string Name { get; set; }
        int Id { get; set; }
        int ComputeNumber();
    }
    public class Person : IPerson
    {
        public string Name { get; set;}
        public int Id { get; set;}
        public Person(string name)
        {
            this.Name = name;
        }

        public int ComputeNumber()
        {
            return this.Id * 2 + 1; 
        }
    }

    [TestClass]
    public class Person_UnitTests
    {
        [TestMethod]
        public void MockAPropertyFromAnInterface()
        {
            var expectedName = "fred";
            var personMock = new Moq.Mock();
            personMock.SetupGet(m => m.Name).Returns(expectedName);
            Assert.AreEqual(expectedName, personMock.Object.Name);
            personMock.Verify(m => m.Name, Moq.Times.AtLeast(1));
            personMock.Verify(m => m.Name, Moq.Times.AtMost(1));
        }

        [TestMethod]
        public void MockAMethodFromAnInterface()
        {
            var expectedIntValue = 5;
            var personMock = new Moq.Mock();
            personMock.Setup(m => m.ComputeNumber()).Returns(expectedIntValue);
            Assert.AreEqual(expectedIntValue, personMock.Object.ComputeNumber());
            personMock.Verify(m => m.ComputeNumber(), Moq.Times.AtLeast(1));
            personMock.Verify(m => m.ComputeNumber(), Moq.Times.AtMost(1));
        }

        [TestMethod]
        public void MockAPropertyFromAnInterface_Stubbing()
        {
            var expectedName = "fred";
            var personMock = Moq.Mock.Of();
            personMock.Name = expectedName;
            Assert.AreEqual(expectedName, personMock.Name);
        }

        [TestMethod]
        public void MockAProperty_WhichChangeOverTime()
        {
            var personMock = new Moq.Mock();
            var i = 1;
            personMock.SetupGet(t => t.Id).Returns(() => i).Callback(() => i++);
            Assert.AreEqual(1, personMock.Object.Id);
            Assert.AreEqual(2, personMock.Object.Id);
            Assert.AreEqual(3, personMock.Object.Id);
            personMock.Verify(m => m.Id, Moq.Times.Exactly(3));
        }
    }
}


No comments:

Post a Comment