Home > Enterprise >  Mocking UnitOfWork / GenericRepository Implementation
Mocking UnitOfWork / GenericRepository Implementation

Time:04-26

I followed this SO answer to a similar question, (the below is an implentation of the 2nd answer)

I'm trying to figure out how to test:

 public async Task<string> DoWork()
        {
            return await _testRepository.GetAsync(); <-- how do I test here???
        }

Example Class

using System.Threading.Tasks;
using Test.DataAccess.Core;
using Test.DataAccess.Repository;

namespace Test.DataAccess
{
    public class TestManager : ITestManager
    {
        private IUnitOfWork _unitOfWork;
        private ITestRepository _testRepository;

        public TestManager(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _testRepository = _unitOfWork.GetRepository<TestRepository>();
        }
        
        public async Task<string> DoWork()
        {
            return await _testRepository.GetAsync();
        }

    }
}

Example Repo Link:

Class Link

Repo Link

CodePudding user response:

It depends. What are you trying to test? If you need to mock your ITestRepository that is being built by your IUnitOfWork, with NSubstitute you can do something like:

public class SomeTestClass
{
    public void SomeTest()
    {
        var repository = Substitute.For<ITestRepository>();
        var unitOfWork = Substitute.For<IUnitOfWork>();
        unitOfWork.GetRepository<TestRepository>().Returns(repository);
    }
}

In that case you`ll mock both repository and uow and make the uow return the mock repo.

  • Related