I am new to Moq and want to use it as a data warehouse to store data, but without touching a live database.
My setup is as follows:
- UnitOfWork contains all repositories and is used to access data throughout the application.
- The repository is a direct binding to DbSet provided by DbContext.
- DbContext contains all DbSets.
Here is my test:
var user = new User()
{
FirstName = "Some",
LastName = "Guy",
EmailAddress = "some.guy@mockymoqmoq.com",
};
var mockSet = new MockDbSet<User>();
var mockContext = new Mock<WebAPIDbContext>();
mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);
using (var uow = UnitOfWork.Create(mockContext.Object))
{
uow.UserRepository.Add(user);
uow.SaveChanges();
}
mockSet.Verify(u => u.Add(It.IsAny<User>()), Times.Once());
My test seems successful, as it can verify that the user has been added to the DbSet layout, but I need to do this in order to return the data and perform additional statements on it (this is just an ad-hoc test).
Please advise to test the frameworks. In addition, I have the opportunity to switch to other testing frameworks, if they are more convenient to use.
.
: .
Unit Test
var user = new User()
{
FirstName = "Some",
LastName = "Guy",
EmailAddress = "some.guy@mockymoqmoq.com",
};
var mockSet = new MockDbSet<User>();
var mockContext = new Mock<WebAPIDbContext>();
mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);
using (var uow = UnitOfWork.Create(mockContext.Object))
{
uow.UserRepository.Add(user);
uow.SaveChanges();
}
mockSet.Verify(u => u.Add(It.IsAny<User>()), Times.Once());
}
MockDbSet
class MockDbSet<TEntity> : Mock<DbSet<TEntity>> where TEntity : class
{
public ICollection<TEntity> BackingStore { get; set; }
public MockDbSet()
{
var queryable = (this.BackingStore ?? (this.BackingStore = new List<TEntity>())).AsQueryable();
this.As<IQueryable<TEntity>>().Setup(e => e.Provider).Returns(queryable.Provider);
this.As<IQueryable<TEntity>>().Setup(e => e.Expression).Returns(queryable.Expression);
this.As<IQueryable<TEntity>>().Setup(e => e.ElementType).Returns(queryable.ElementType);
this.As<IQueryable<TEntity>>().Setup(e => e.GetEnumerator()).Returns(() => queryable.GetEnumerator());
this.Setup(e => e.Add(It.IsAny<TEntity>())).Returns((TEntity entity) =>
{
this.BackingStore.Add(entity);
return entity;
});
}
}