Mocking DbContext for TDD Repository

﹥>﹥吖頭↗ 提交于 2019-12-23 00:50:08

问题


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

    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/27131073/mocking-dbcontext-for-tdd-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!