I'm building the unit tests for a C# MVC5 Project using Entity Framework 6. I'm trying to mock my BlogRepository using Moq which will then be used as an argument for the BlogController which I am attempting to test. I actually have the unit test working fine, but to do this I created a Fake BlogRepository Class, when I would much rather work out how to do it using Moq.

The problem I'm getting is that the Controller wants the argument to be of type IBlogRepository but is only seeing it as Mock. So I get an invalid arguments error. I thought this was how it was meant to be used though.

Here is my attempt at creating the mock:

Mock<IBlogRepository> blogRepo = new Mock<IBlogRepository>();
blogRepo.Setup(t => t.GetBlogByID(It.IsAny<int>())).Returns<Blog>(blog => new Blog());

And here is the beginning of the controller:

public class BlogController : Controller
{
    IBlogRepository blogRepo;

    public BlogController(IBlogRepository repoBlog)
    {
        blogRepo = repoBlog;
    }

What am I doing wrong? or have I got the wrong idea here. Any help would be appreciated. Thanks.

有帮助吗?

解决方案

You should pass blogRepo.Object not blogRepo to your controller.

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