简体   繁体   中英

Mocking DbContext with Moq Mock object without declaring interface

I have an EFDbContext which declares the Entity framework database context.

I do not need an interface for it and yet I am apparently forced by Moq to only be able to mock interfaces.

Is there a way to mock a concrete method but just treat it as an interface?

The code is breaking:

[TestClass]
public class EFBlogRepositoryTest
{
    [TestMethod]
    public void Test_GetAllBlogs()
    {

        // Arrange
        DateTime now = DateTime.Now;

        var mockDbContext = new Mock<EFDbContext>();
        var blogRepository = new EFBlogRepository(mockDbContext.Object);

        List<Blog> blogs = new List<Blog> {                 
            new Blog { BlogID = 1, Description = "1", Status = true, PublishDate = now },
            new Blog { BlogID = 2, Description = "2", Status = true, PublishDate = now }
        };

        mockDbContext.Setup(c => c.Blogs).Returns(blogs); // ERROR OCCURS HERE

        // Act
        List<Blog> result = blogRepository.GetAllBlogs(1, 2, SortDirection.DESC, null, null).ToList();

        // Assert     

        Assert.AreEqual(2, result.Count());
    }
}

No, that's not how it works. A mock object is a (partial) implementation of an interface as an alternative to the actual implementation.

So when you say

I do not need an interface for it

... you do now.

Only method/properties on interfaces, or virtual methods/properties on classes can be mocked.

So, you either need an interface (which is what you should do), or if you really, really don't want to, then you can declare .Blogs as virtual.

Mind you, that to set a property, you should use .SetupGet, not the Setup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM