Why is my mock set empty?

戏子无情 提交于 2019-12-08 15:24:28

Why is my mock set empty?

Because you didn't configure (setup) it to take any action when you insert data to it. When a mock is created it "loses" all the logic that was present on the original class and marked virtual. Moq simply overrides such methods so that later you can configure them to do anything (return value, throw, etc).

Naturally, you can setup Add method to insert data back to your data blog list:

var mockSet = new Mock<DbSet<Blog>>();
mockSet.Setup(m => m.Add<It.IsAny<Blog>()).Callback(blog => data.Add(blog));

When Add method will be invoked on your DbSet (preferrably via call to service) configured version of Add will take over and insert blog to your data list (Callback method tells Moq to "invoke this code" when mocked method is called).

You could also try to prevent overriding of Add by using CallBase parameter. However, this might not work as your DbSet is not aware of list existence, you'll most likely have to configure it more heavily then.

On a final note, once your experiment crystallizes you should realize that configuring Add won't be necessary because you won't be checking whether blog was added via GetAllBlogs method but rather by verification on the mock itself:

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

Did you try to use CallBase property?

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