Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock a Repository to use as an argument for a Controller?

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.

like image 658
AndrewPolland Avatar asked Mar 28 '14 22:03

AndrewPolland


1 Answers

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

like image 155
Oleksandr Kobylianskyi Avatar answered Oct 29 '22 18:10

Oleksandr Kobylianskyi