Mocking or faking DbEntityEntry or creating a new DbEntityEntry
Solution 1:
Just like the other case, what you need is to add an additional level of indirection:
interface ISalesContext
{
IDbSet<T> GetIDbSet<T>();
void SetModified(object entity)
}
class SalesContext : DbContext, ISalesContext
{
public IDbSet<T> GetIDbSet<T>()
{
return Set<T>();
}
public void SetModified(object entity)
{
Entry(entity).State = EntityState.Modified;
}
}
So, instead of calling the implementation, you just call SetModified
.
Solution 2:
Found this question when I needed to unit test with Moq
, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified
can be used with object as well.
DbContext:
public class AppDbContext : DbContext
{
...
public virtual void SetModified(GuidEntityBase entity)
{
Entry(entity).State = EntityState.Modified;
Entry(entity).Property(x => x.CreatedDate).IsModified = false;
Entry(entity).Property(x => x.CreatedBy).IsModified = false;
}
...
}
Test:
var mockContext = new Mock<AppDbContext>();
mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));