title: Unit Testing Unit of Work and Generic Repository Pattern framework using Moq
body: <p>I am unit testing a Service which is using the a Unit of Work and Generic Repository using Moq. The problem is that in the service class the _subsiteRepository is always null when I run the test in debug mode.</p>
  
  <p>The setup of the Service Class I am mocking</p>
  
  <pre><code>private readonly IRepository&lt;Subsite&gt; _subsiteRepository;
  
  public PlatformService(IUnitOfWork&lt;PlatformContext&gt; unitOfWork)
  {
      _subsiteRepository = unitOfWork.GetRepository&lt;Subsite&gt;();
  }
  </code></pre>
  
  <p>and the method in this class that am testing. The problem is that _subsiteRepository is always null. The method does more than this but this is the relevant part.</p>
  
  <pre><code>public async Task&lt;IEnumerable&lt;Subsite&gt;&gt; GetSubsites()
  {
      // Get Subsites
      var subsites = await _subsiteRepository
          .GetAll()
          .ToListAsync();
  }
  </code></pre>
  
  <p>Finally this is the test I am running:</p>
  
  <pre><code>private readonly Mock&lt;IRepository&lt;Subsite&gt;&gt; _subsiteRepository;
  private readonly Mock&lt;IUnitOfWork&lt;PlatformContext&gt;&gt; _unitOfWork;
  private readonly PlatformService _platformService;
  
  _subsiteRepository = new Mock&lt;IRepository&lt;Subsite&gt;&gt;();
  _unitOfWork = new Mock&lt;IUnitOfWork&lt;PlatformContext&gt;&gt;();
  _platformService = new PlatformService(_unitOfWork.Object);
  
  // Arrange
  var fakeSubsites = new List&lt;Subsite&gt;
  {
      new Subsite {IDSubsite = new Guid(), Title = "Subsite One"}
  }.AsQueryable();
  
  _unitOfWork.Setup(x =&gt; x.GetRepository&lt;Subsite&gt;()).Returns(_subsiteRepository.Object);
  _unitOfWork.Setup(x =&gt; x.GetRepository&lt;Subsite&gt;().GetAll()).Returns(fakeSubsites);
  
  // Act
  var subsites = await _platformService.GetSubsites(null, null);
  
  // Assert
  Assert.NotNull(subsites);
  </code></pre>