Separate DbContexts modifying the same DbSet during unit tests
Environment:
Xunit 2.3.1
Microsoft.EntityFrameworkCore.InMemory 2.1.0
I have three test methods in three different classes that when run separately pass but when run together only one will pass and the other two will fail. Then when the two are run again - one will pass and the other will fail.
I've found the issue, I'm just not sure why it is happening.
I'll show some code and below the code are design explanations.
The gist:
Three test classes:
public class PeerReviewRepositoryTest
public class EotReviewByAoRepositoryTest
public class EotReviewRepositoryTest
The test methods(They are all name the same):
public void GetReviewDataTest(){} //in PeerReviewRepositoryTest
public void GetReviewDataTest(){} //in EotReviewByAoRepositoryTest
public void GetReviewDataTest(){} //in EotReviewRepositoryTest
Note: all three test methods look very similar in that they create a distinct options via GUID, a new context, a new repo object, and call a method on that repo object that queries the Users DbSet e.g. _context.Users.Single(x=> x.Id == document.AuthorId)
See some more code below of two of the tests and classes fleshed out:
PeerReview class:
namespace AloeWeb.Models.Repositories
{
public class PeerReviewRepository : IPeerReviewRepository
{
private AloeDbContext _context;
public PeerReviewRepository(AloeDbContext context)
{
_context = context;
}
public PeerReviewDM GetReviewData(int documentId)
{
PeerReviewDM dm = new PeerReviewDM();
ItemInstancesDocumentInstance document = _context.ItemInstancesDocumentInstance
.Include(x => x.ItemInstancesDocumentFieldValue)
.ThenInclude(x => x.IdNavigation)
.Include(x=>x.IdNavigation)
.Single(x => x.Id == documentId);
LoadDomainModel(dm, document);
dm.ReviewerToApproved = new KeyValuePair<string, bool>(_context.Users.Single(x => x.Id == document.AuthorId).Name, document.IsPeerReviewApproved);
return dm;
}
}
}
The Exception can be thrown on line dm.ReviewerToApproved = new KeyValuePair<string, bool>(_context.Users.Single(x => x.Id == document.AuthorId).Name, document.IsPeerReviewApproved); because no record is found
Peer Review tests
namespace AloeWebUnitTest.RepositoryTests
{
[Trait("Repository", "")]
public class PeerReviewRepositoryTest
{
[Fact(DisplayName = "GetReviewDataTest")]
[Trait("Repository", "PeerReviewRepository")]
public void GetReviewDataTest()
{
var options = new DbContextOptionsBuilder<AloeDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
using (AloeDbContext context = new AloeDbContext(options))
{
SeedDb(context);
AddData(context);
PeerReviewRepository repository = new PeerReviewRepository(context);
PeerReviewDM dm = repository.GetReviewData(context.ItemInstancesDocumentInstance.First().Id);
PeerReviewDM expectedDM = new PeerReviewDM()
{
Duration = "Review Duration (hrs)",
Implementors = "Implementor(s)",
ItemsReviewed = "Items Reviewed",
Defects = "Defects",
Checkboxes = new SolutionCheckBoxes()
{
EotSuggestions = "True",
EiTagged = "True",
CodeCommented = "True",
TestNotBroken = "True",
HeaderTool = "True",
HeaderCommented = "True",
TestCodeAdded = "True",
CodeTestsEi = "True",
WrapperVerificationUpdated = "True",
CorrectWrapper = "True",
RegressionTesting = "True",
RegressionTestsEi = "True",
UutTested = "True",
RegressionTestLog = "True",
Documentation = "True",
VidsUpdated = "True"
}
};
Assert.Equal(expectedDM, dm);
}
}
protected void SeedDb(SDRDBContext context)
{
context.Add(new ItemDescriptionsProcessDescription() { Id = 1, IdNavigation = new ItemDescriptions() { Id = 1, Name = "EI" } });
CreateDocumentDescriptions(context);
CreateTaskDescriptions(context);
CreateDocumentFieldDescriptions(context);
CreateDocumentReviewDescriptions(context);
CreateProcessFieldDescriptions(context);
AddUsersWithRoleData(context);
context.SaveChanges();
}
private void AddUsersWithRoleData(AloeDbContext context)
{
List<Roles> roles = new List<Roles>()
{
//roles created
};
context.AddRange(roles);
List<Users> users = new List<Users>()
{
new Users { Name = "Admins" },
new Users { Name = "All Users"},
new Users { Name = "SIL"},
new Users { Name = "CCB"},
new Users { Name = "user1"},
new Users { Name = "user2"},
new Users { Name = "user3"},
new Users { Name = "user4"},
new Users { Name = "user5"},
new Users { Name = "user6"} //userId = 10
};
context.AddRange(users);
List<RoleUser> roleUsers = new List<RoleUser>()
{
//role associations created
};
context.AddRange(roleUsers);
}
}
EotReviewByAoRepo class
namespace AloeWeb.Models.Repositories
{
public class EotReviewByAORepository : IEotReviewByAORepository
{
private AloeDbContext _context;
public EotReviewByAORepository(AloeDbContext context)
{
_context = context;
}
public EotReviewDM GetReviewData(int documentId)
{
EotReviewDM dm = new EotReviewDM();
ItemInstancesDocumentInstance document = _context.ItemInstancesDocumentInstance
.Include(x => x.IdNavigation)
.Include(x => x.ItemInstancesDocumentFieldValue)
.ThenInclude(x => x.IdNavigation)
.Single(x => x.Id == documentId);
LoadDomainModel(dm, document);
dm.ReviewerToApproved = new KeyValuePair<string, bool>(_context.Users.Single(x => x.Id == document.AuthorId).Name, document.IsEotReviewApproved);
//get Eot doc id
int relatedEotRevTaskid = _context.TaskInstanceDocumentInstance
.AsNoTracking().Single(x => x.DocumentInstancesId == documentId).TaskInstancesId;
ItemInstancesTaskInstance relatedEotRevTask = _context.ItemInstancesTaskInstance
.AsNoTracking().Single(x => x.Id == relatedEotRevTaskid);
dm.RelatedEotDocumentId = ItemInstancesProcessInstance.GetLatestEotIdByDate(_context, relatedEotRevTask.ProcessInstanceId, document.IdNavigation.CompletedDate );
return dm;
}
//Other methods excluded for brevirty
}
}
EotReviewByAoRepoTest
namespace AloeWebUnitTest.RepositoryTests
{
[Trait("Repository", "")]
public class EotReviewByAORepositoryTest
{
[Fact(DisplayName = "GetReviewDataTest")]
[Trait("Repository", "EotReviewByAORepository")]
public void GetReviewDataTest()
{
var options = new DbContextOptionsBuilder<AloeDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
using (AloeDbContext context = new AloeDbContext(options))
{
SeedDb(context);
AddData(context);
EotReviewByAORepository repository = new EotReviewByAORepository(context);
EotReviewDM dm = repository.GetReviewData(context.ItemInstancesDocumentInstance.Last().Id);
EotReviewDM expectedDM = new EotReviewDM()
{
AnalysisComments = "Root Cause Analysis Comments",
CurrentStateComments = "Current State Comments",
GeneralComments = "General Comments",
SolutionComments = "Recommended Solution Comments",
WorkaroundsComments = "Suggested Workarounds Comments",
RelatedEotDocumentId = context.ItemInstancesDocumentInstance.First(x => x.DescriptionId == 26).Id,
ReviewDuration = "Review Duration (hrs)",
ReviewerToApproved = new KeyValuePair<string, bool>("user1", false),
};
Assert.Equal(expectedDM, dm);
}
}
protected void SeedDb(AloeDbContext context)
{
context.Add(new ItemDescriptionsProcessDescription() { Id = 1, IdNavigation = new ItemDescriptions() { Id = 1, Name = "EI" } });
CreateDocumentDescriptions(context);
CreateTaskDescriptions(context);
CreateDocumentFieldDescriptions(context);
CreateDocumentReviewDescriptions(context);
CreateProcessFieldDescriptions(context);
AddUsersWithRoleData(context);
context.SaveChanges();
}
private void AddUsersWithRoleData(AloeDbContext context)
{
List<Roles> roles = new List<Roles>()
{
//Creating roles
};
context.AddRange(roles);
List<Users> users = new List<Users>()
{
new Users { Name = "Admins" },
new Users { Name = "All Users"},
new Users { Name = "SIL"},
new Users { Name = "CCB"},
new Users { Name = "user1"},
new Users { Name = "user2"},
new Users { Name = "user3"},
new Users { Name = "user4"},
new Users { Name = "user5"},
new Users { Name = "user6"} //userId = 10
};
context.AddRange(users);
List<RoleUser> roleUsers = new List<RoleUser>()
{
//Adding Role associates here
};
context.AddRange(roleUsers);
}
}
}
Design Explanations:
Originally the test classes all inherited from a base class that defined SeedDb(AloeDbContext) and all its containing methods.
The base class also had a method called GetContextWithData() that returned a new AloeDbContext which had it's tables populated via SeedDb()
I moved it all out of there for concern inheritance was messing something up.
The issue:
All three test methods create a repository object and call a method to get the respective review data. In those methods a call is made to the Users dbSet e.g. _context.Users.Single(x=> x.Id == document.AuthorId). In all three of the tests document.AuthorId is equal to 5. Somehow all three calls of AddUsersWithRoleData are adding users to seemingly the same DbSet<Users>
So, only one DbSet
I've tried:
Making the tests run in order. Doesn't work
Declaring Ids for the users when added to the DbContext. Fixes this issue but breaks other tests that add Users to the DbSet
Further technical details
EF Core version: 2.1 Database Provider: InMemory Operating system: Win10 IDE: Visual Studio 2017
Pretty sure this is because of the issues discussed in #6872
@JohnCOsborne My first guess is that your code is sharing the same in-memory database, but that doesn't fit everything you said. Beyond that, I'm finding it hard to follow what you are doing. Can you post a runnable project/solution or complete code listing that demonstrates the behavior you are seeing?
Each test creates a fresh options to use var options = new DbContextOptionsBuilder<MyAppDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
I could post it but it would take me a moment... I'd rather make the first post easier to follow but will get you the code listing if you'd like. The more I read through #6872 the more I think they are directly related, especially since I hardcoded the Ids in AddUsersWithRoleData and all three tests passed which is what @ardalis mentioned in #6872.
All three test methods create a repository object and call a method to get the respective review data. In those methods a call is made to the Users dbSet e.g. _context.Users.Single(x=> x.Id == document.AuthorId). In all three of the tests document.AuthorId is equal to 5
Running same piece of code in 3 different in memory database will give same results. Your seed data is same and your query is same. Why do you expect the resulting document's Id to be different especially you are retrieving it like thiscontext.ItemInstanceDocumentInstance.Last().Id?
Planning on adding adding more code today and removing some ambiguity...
...but in the meantime. The three distinct test methods, create three distinct repository objects(different class definitions) but all those class definitions have a method that queries the DbSet<Users>
So when a repository method is called and the query _context.Users.Single(x=> x.Id == document.AuthorId) is executed one test method's context will contain, in it's Users DbSet, Users entities with Ids (1,3,4,5,8,10,11,14,16,17) and then in another the Users will have Ids (2,6,7,9,12,13,15,18,19,20).
I've updated the code samples. I hope that helps.
Thanks!
@JohnCOsborne I am still not able to run this code.
EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.