Skip to content

Instantly share code, notes, and snippets.

@kiwipom
Last active December 16, 2015 10:08
Show Gist options
  • Select an option

  • Save kiwipom/5417410 to your computer and use it in GitHub Desktop.

Select an option

Save kiwipom/5417410 to your computer and use it in GitHub Desktop.
Moq doesn't verify the mapper gets invoked within a .Select method
public class TheTest
{
[TestMethod]
public void TestThisThing()
{
var mockMapper = new Mock<IMapper>();
var mockDataAccess = new Mock<IDataAccess>();
var repositoryUnderTest = new Repository(mockMapper.Object);
// Create 2 data entities
var dataEntities = new { new DataEntity(), new DataEntity() };
// And have the mock DataAccess bit return them...
mockDataAccess
.Setup(da => da.Get(It.IsAny<Query>()))
.Returns(dataEntities);
repositoryUnderTest.Get(dataEntities);
// check that the mapper fired twice
mockMapper.Verify(m => m.Transform(It.IsAny<DataEntity>()), Times.Exactly(2));
}
}
public class Repository
{
private readonly IMapper _mapper;
private readonly IDataAccess _dataAccess;
public Repository(IMapper mapper, IDataAccess dataAccess)
{
_mapper = mapper;
_dataAccess = dataAccess;
}
// With this implementation of Get,
// The test fails, as Moq does not notice the _mapper.Transform
// gets invoked within the .Select method.
public IEnumerable<DomainEntity> Get(Query query)
{
/* get the data from the ORM based on the query */
IEnumerable<DataEntity> results = _dataAccess.Get(query);
return results
.Select(entity => _mapper.Transform(entity));
}
// With this implementation of Get,
// The test passes, as Moq *does* notice the _mapper.Transform
// gets invoked within the foreach loop.
public IEnumerable<DomainEntity> Get(Query query)
{
/* get the data from the ORM based on the query */
IEnumerable<DataEntity> results = _dataAccess.Get(query);
var domainEntities = new List<DomainEntity>();
foreach (var result in results)
{
domainEntities.Add(_mapper.Transform(result));
}
return domainEntities;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment