I have a repository in my application that looks something like this:

public interface IUserRepository
{
    void CreateUser(User user);
    void Save();
}

public class UserRepository : IUserRepository
{
    public void CreateUser(User user)
    {
        // UsersContext is injected through Unity
        if(user != null)
            this.UsersContext.Users.Add(user);
    }

    public void Save()
    {
        this.UsersContext.SaveChanges();
    }
}

I am follwing this MSDN article on unit testing using Entity Framework. My test method looks like this:

[TestMethod]
public void CreateUser_Test()
{
    var mockSet = new Mock<DbSet<User>>();

    var mockContext = new Mock<UsersContext>();
    mockContext.Setup(m => m.Users).Returns(mockSet.Object);

    var repo = new UserRepository(mockContext.Object);
    repo.CreateUser(new User {Name = "Sample User", Age = 23});
    repo.Save();

    // Assert fails, nothing is added to the mocked DbSet.
    Assert.AreEqual(1, mockSet.Object.Users.Count());
}

I am not able to test if the object I am trying to create is really added to the mocked DbSet. The MSDN article does not help either, it just tests that the methods are called and does not test that the object is added to the mocked DbSet. Is there any way I can verify that the object I created is added to the mocked DbSet?

有帮助吗?

解决方案

You are testing a non-query scenario (http://msdn.microsoft.com/en-us/library/dn314429.aspx#nonQuery). Moq has the Verify method for this purpose:

 mockSet.Verify(m => m.Add(It.IsAny<User>()), Times.Once());
 mockContext.Verify(m => m.SaveChanges(), Times.Once());

As an aside, you probably don't want the Save() method on your repository. I'd suggest investigating the Unit of Work pattern, which will allow you to coordinate changes across different repositories by ensuring they all share the same context.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top