Last active
December 16, 2015 10:08
-
-
Save kiwipom/5417410 to your computer and use it in GitHub Desktop.
Moq doesn't verify the mapper gets invoked within a .Select method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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