I've written a test to validate a small piece of new functionality which calls a large middleware function with a ton of logic in it that converts one type of User (an ASP Net Membership User) to an internal one (SystemUser). It's a messy system, but I can't rip it out, hence the new tests.
My test calls into a GetAllActiveUsers()
method which calls down a few layers and eventually gets to an enumeration that's causing problems. The test has a mocked up entity framework datacontext Mock<localEntities> mockDb
which is Setup as follows:
[SetUp]
public void Setup()
{
var mockUserSet = new Mock<DbSet<User>>();
this.mockDb = new Mock<localEntities>();
this.mockMembershipService = new Mock<IMembershipService>();
this.mockRoleService = new Mock<IRoleService>();
this.mockUserAgreementRelation = new Mock<DbSet<UserAgreementRelation>>();
this.testUsers = this.CreateSystemUsers();
this.mockDb.Setup(m => m.User).Returns(mockUserSet.Object);
mockUserAgreementRelation.SetupAllProperties();
var agreementRelations = this.testUsers.Select(u => new UserAgreementRelation() { AgentUserID = u.UserId, IsDeleted = null });
mockUserAgreementRelation.As<IQueryable<UserAgreementRelation>>().Setup(ua => ua.GetEnumerator()).Returns(agreementRelations.GetEnumerator());
this.mockDb.Setup(m => m.UserAgreementRelation).Returns(mockUserAgreementRelation.Object);
}
In my test I setup some users and call into var testActiveUsers = testRepo.GetAllActiveUsers();
which calls the problem line.
Here's where I get confused.
The test passes with this code:
var agreementRelations = databaseContext.UserAgreementRelation().ToList();
var userAgreementFromDB = agreementRelations
.FirstOrDefault(x => x.AgentUserID == ramsUser.UserId && (x.IsDeleted == null || !(bool)x.IsDeleted));
but fails with this code:
var userAgreementFromDB = databaseContext.UserAgreementRelation
.FirstOrDefault(x => x.AgentUserID == ramsUser.UserId && (x.IsDeleted == null || !(bool)x.IsDeleted));
Additionally, if I debug and step through the code, I can use a quick watch on the mocked UserAgreementRelation once. The first time I will see a UserAgreementRelation for each user I'm testing. If I run the watch again the enumeration yields no results even though the code hasn't advanced. I'm guessing this is related to the issue. However, since I've no idea why it's happening, I can't say how it might cause this problem.
Keep in mind that the simpler code (without the ToList()) is production code. It's currently functioning fine, but my test fails. Since this is a direct database call, enumerating the entire UserAgreementRelation table isn't a viable solution.
Suggestions?