The examples I\'ve seen for using moq for a repository only show how to mock things being returned. I have a somewhat strange requirement: when a query is executed, if a conditi
You can do this by mocking the DbSet.Add()
method, like so:
[Fact]
public void CreateBlog_saves_a_blog_via_context()
{
var data = new List
{
new Blog { Name = "BBB" },
new Blog { Name = "ZZZ" },
new Blog { Name = "AAA" },
};
var mockSet = new Mock>();
mockSet.Setup(blogs => blogs.Add(It.IsAny)).Returns(blog =>
{
data.Add(blog);
return blog;
});
var mockContext = new Mock();
mockContext.Setup(m => m.Blogs).Returns(mockSet.Object);
var service = new BlogService(mockContext.Object);
var blog = service.AddBlog("_ADO.NET Blog", "http://blogs.msdn.com/adonet");
var blogs = service.GetAllBlogs();
mockSet.Verify(m => m.Add(It.IsAny()), Times.Once());
mockContext.Verify(m => m.SaveChanges(), Times.Once());
Assert.NotNull(blog)
Assert.Equal(4, blogs.Count);
Assert.Equal("AAA", blogs(1).Name);
Assert.Equal("BBB", blogs(2).Name);
Assert.Equal("ZZZ", blogs(3).Name);
}
This is adapted from the documentation found here.