lundi 2 février 2015

Mock same method in a test using Moq with different linq expressions

I have a repository with this method



public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>,
IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");


I have a method that is using it as such to get a user to work on



var user = this.applicationUserRepository.Get(x => x.EmailAddress == userName).FirstOrDefault();


It then calls the same method with a different expression further in the method as follows to check the user working on the first user



var changingUser = this.applicationUserRepository.Get(x => x.Id == changingUserId).FirstOrDefault();


I am trying to mock the repository with two setups to call it twice in the same test.



string emailAddress = "myaddresss@test.com";
int changingUserId = 5;

var targetUsers = new List<ApplicationUser>
{
new ApplicationUser { Id = 1, Password = "Testing123", EmailAddress = emailAddress }
};

// Setup the user that will be modified to be found
var mockApplicationUserRepository = new Mock<IRepository<ApplicationUser>>();
mockApplicationUserRepository
.Setup(aur => aur.Get(x => x.EmailAddress == userName, null, string.Empty))
.Returns(targetUsers.AsEnumerable());


// Set up to query the changing user to not be found
mockApplicationUserRepository
.Setup(aur2 => aur2.Get(x => x.Id == changingUserId, null, string.Empty))
.Returns(new List<ApplicationUser>().AsEnumerable()); // Empty list


Even though the second call will never be hit, for this test, I want to learn how to set this up. When I run the test the first call



var user = this.applicationUserRepository.Get(x => x.EmailAddress == userName).FirstOrDefault();


I get null


If I change the mock to have It.IsAny>>() I get the expected user back.


I can not figure out how I will set the two calls up so it will know which expression to use. Any help will be appreciated.


Aucun commentaire:

Enregistrer un commentaire