Trying to Mock my EF Context which is coupled to my Repository. Im using Moq, trying to setup a mocked Context and pass it into the Repository by the constructor.
After that Im calling the Add method, to simply add a new object which I after that try to Assert by checking if the context i passed in has changed state...
Error Im getting is a NullReference Exception and I guess its because my mocking isn't correct..
This is the code:
Test with not working mock
[TestClass]
public class GameRepositoryTests
{
[TestMethod]
public void PlayerThatWonMustBeAddedToTopList()
{
// Arrange
var expected = "Player added successfully";
var dbContextMock = new Mock<Context>();
// Need to setup the Context??
IRepository gameRepository = new GameRepository(dbContextMock.Object);
var user = "MyName";
// Act
gameRepository.Add(user);
// Assert
dbContextMock.VerifySet(o => o.Entry(new ScoreBoard()).State = EntityState.Added);
}
}
public class ScoreBoard
{
}
Repository
public class GameRepository : IRepository
{
private readonly Context _context;
public GameRepository()
: this(new Context())
{
// Blank!
}
// Passing in the Mock here...
public GameRepository(Context context)
{
this._context = context;
}
// Method under test...
public void Add<T>(T entity) where T : class
{
_context.Set<T>().Add(entity);
}
}
Context
public class Context : DbContext
{
public Context()
: base("name=DefaultConnection")
{
}
}
You need to mock out the Set<T>()
call.
Something like this should work out.
// Arrange
var context = new Mock<Context>();
var set = new Mock<DbSet<User>>();
context.Setup(c => c.Set<User>()).Returns(set.Object);
// Act
// Assert
set.Verify(s => s.Add(It.IsAny<User>()), Times.Once());
You don't really need to make verify anything except that Add()
was called on the underlying DbSet
. Doing your verify on the fact that the Entity state was modified is unnecessary. If you verify that Add()
was called that should be enough as you can safely assume that EF is working properly.
This example only works for repositories for your User object. You would have to setup the mocks differently for each repository you want to test in this way. You could probably write up a more generic version of this if needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.