How do you mock adding items to a repository or DbContext using moq?

前端 未结 5 1117
猫巷女王i
猫巷女王i 2021-01-23 17:00

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

5条回答
  •  囚心锁ツ
    2021-01-23 17:33

    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.

提交回复
热议问题