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")
{
}
}