Friday, September 18, 2015

Perform Unit Test using AutoFixture.AutoFakeItEasy



AutoFixture could be auto mocking container for many mocking library including Moq, Rhino Mocks and many more. We can use AutoFixture as auto mocking container with FakeItEasy as well.
To install AutoFixture with FakeItEasy, use this command to console 

Install-Package AutoFixture.AutoFakeItEasy

Let’s implement one sample program to perform unit test.
public interface IRepository
    {
        string Hello();
    }

    public class PersonRepo : IRepository
    {
        IRepository objPerson;

        public PersonRepo() { }
        public PersonRepo(IRepository p)
        {
            this.objPerson = p;
        }

        public string Hello()
        {
            return "Sourav Kayal";
        }
    }


   
    public interface IConsumer
    {
        string Execute();
    }
    class Consumer : IConsumer
    {
     
        IRepository Repo;
        public Consumer( IRepository Repo)
        {
          this.Repo = Repo;
        }
        public string Execute()
        {
           return  Repo.Hello();
        }
    }
}

The program is very simple, Just we have introduce concept of IoC. Now, we will write Unit test for same.

public class UnitTestClass
    {
        [TestMethod]
        public void est_Function()
        {
            //Arrange
            var fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());
            var fake = fixture.Freeze<Fake<IRepository>>();
            fake.CallsTo(x => x.Hello()).Returns("Dumy Data");

            //Act
            var result = fixture.CreateAnonymous<IConsumer>();
            result.Execute();

            //Verify
            A.CallTo(() => result.Execute()).MustHaveHappened();
           
        }
    }


No comments:

Post a Comment