Search code examples
c#unit-testingrepositorymoqbusiness-logic

Mock service that takes unitOfWork in constructor


I try to write unit tests on my business logic.

What i have now :

private Mock<IRepository<Theme>> _mockRepository;
    private IBaseService<Theme> _service;
    private Mock<IAdminDataContext> _mockDataContext;
    private List<Theme> _listTheme;

    [TestInitialize]
    public void Initialize()
    {
        _mockRepository = new Mock<IRepository<Theme>>();
        _mockDataContext = new Mock<IAdminDataContext>();
        _service = new ThemeService(_mockDataContext.Object);
        _listTheme = new List<Theme>
                     {
                         new Theme
                         {
                             Id = 1,
                             BgColor = "red",
                             BgImage = "/images/bg1.png",
                             PrimaryColor = "white"
                         },
                         new Theme
                         {
                             Id = 2,
                             BgColor = "green",
                             BgImage = "/images/bg2.png",
                             PrimaryColor = "white"
                         },
                         new Theme
                         {
                             Id = 3,
                             BgColor = "blue",
                             BgImage = "/images/bg3.png",
                             PrimaryColor = "white"
                         }
                     };
    }

    [TestMethod]
    public async Task ThemeGetAll()
    {
        //Arrange
        _mockRepository.Setup(x => x.GetAll()).ReturnsAsync(_listTheme);

        //Act
        List<Theme> results = await _service.GetAll();

        //Assert
        Assert.IsNotNull(results);
        Assert.AreEqual(_listTheme.Count, results.Count);
    }

Problem - on service GetAll i get exception because object is null. Object - this is repository. Here are code-details :

public class BaseService<T> : DomainBaseService, IBaseService<T> where T : BaseEntity
    {
        private readonly IAdminDataContext _dataContext;
        private readonly IRepository<T> _repository;

        public BaseService(IAdminDataContext dataContext)
            : base(dataContext)
        {
            this._dataContext = dataContext;
            this._repository = dataContext.Repository<T>();
        }

        public async Task<List<T>> GetAll()
        {
            return await _repository.GetAll();
        }
    }

As you can see, in service i try to get repository from unitOfWork (AdminDataContext). But it is always null.

How i should mock my service to test its functionality?


Solution

  • You never setup the Repository method to return your mock repository. Just add the following to the "arrange" portion of your test:

    _mockDataContext.Setup(x => x.Repository<Theme>()).Returns(_mockRepository.Object);