Using Moq for testing

Install the nuget Moq package. Below is a simple example to create a mock for a database implementation (which is also a mock :-)).

namespace ConsoleApp1
{
    using Moq;
    using System;
    using System.Collections.Generic;

    public interface IDAL
    {
        List<string> RetrieveBooks();
    }

    public class DAL : IDAL
    {
        public List<string> RetrieveBooks()
        {
            return new List<string> { "a", "b", "c" };
        }
    }

    public class BookManager
    {
        private IDAL _dal;

        public BookManager(IDAL dal)
        {
            _dal = dal;
        }

        public List<string> GetBooks()
        {
            return this._dal.RetrieveBooks();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*
             * Bookmanager with database implementation
             */
            Console.WriteLine("Database implementation");
            BookManager bmDB = new BookManager(new DAL());
            bmDB.GetBooks().ForEach(i => Console.WriteLine(i));

            /*
             * Bookmanager with a mock database
             */
            Console.WriteLine("Database mock implementation");
            var dal_mock = new Mock<IDAL>();
            dal_mock.Setup(i => 
               i.RetrieveBooks()).Returns(new List<string> { "d" });
            BookManager bmMOQ = new BookManager(dal_mock.Object);
            bmMOQ.GetBooks().ForEach(i => Console.WriteLine(i));
        }
    }
}

Share

Leave a Reply

Your email address will not be published. Required fields are marked *