'DbContext Mocking ChangeTracker with xUnit - Entity Framework
I am currently trying to track changes done to the entities. The application is an ASP.NET MVC app using Entity Framework. Within the repository I use a basic command for saving
DbContext.SaveChangesAsync()
However, before that I would like to check what have changed in the entity and thus I use
DbContext.ChangeTracker.Entries<TEntity>();
All works fine when I am running the solution, but starting up the xUnit unit tests returns an error
System.InvalidOperationException : No connection string named "XXXX" could be found in the application config file
It seems like the mocking that I do doesn't mock the ChangeTracker - how can I achieve it so that I can mock the change tracker? Is there maybe other option how to prevent such a problem? How do you normally mock the DbContext so that it covers the change tracker as well?
Example of the code:
public virtual async Task UpdateAsync(params TEntity[] items)
{
foreach (var item in items.Where(i => i != null).ToList())
{
if (item.Id == 0)
{
throw new CustomException(CustomExceptionReason.CannotUpdateNotCreated, item.Id.ToString());
}
DbContext.ChangeTracker.DetectChanges();
var otherCHanges = DbContext.ChangeTracker.Entries<TEntity>();
UpdateModifiedDate(item);
}
await this.DbContext.SaveChangesAsync();
foreach (var item in items)
{
CacheRemove(item);
}
}
Example of mocking:
var users = new[] { new User {Id = 1, UserName = "TestUserName", FirstName = "Test", LastName = "User"} };
var dbContextMock = new DbContextMock<MyEntities>();
dbContextMock.CreateDbSetMock(x => x.Users, (e, c) => e.Id, users);
Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
