Cannot mock method call in ASP.NET MVC Controller using Moq

I have the following code in the "UserController" in my ASP.NET MVC application:

public class UserController : Controller
{
    public ActionResult Index()
    {
        return RedirectToAction("List");
    }

    public ActionResult List()
    {
        IUserRepository repo = new UserRepository();
        IQueryable<Business.Entities.User> users = repo.GetAll();
        return View("List", users);
    }
}

Using Moq, I would like to make fun of the database call "repo.GetAll ()". Here is what I have for my test:

[Test]
public void List()
{
    Mock<IUserRepository> mockRepo = new Mock<IUserRepository>();
    mockRepo.Setup(ur => ur.GetAll()).Returns(MockedGetAll());
    var v = mockRepo.Object.GetAll();

    var controller = new UserController();
    var result = controller.List() as ViewResult;
    var model = result.ViewData.Model as IQueryable<User>;

    Assert.AreEqual("List", result.ViewName);
    Assert.IsNotNull(model);
    Assert.Greater(model.Count(), 0);
}

I also have a function that would return some static data to run the test:

private IQueryable<User> MockedGetAll()
{
    List<User> users = new List<User>();
    users.Add(new User(1, "mark.paterson", "mark.paterson@yahoo.com", "Mark", "Paterson", false, true));
    users.Add(new User(2, "nikki.paterson", "nikki.paterson@yahoo.com", "Nikki", "Paterson", false, true));
    return users.AsQueryable();
}

Test aborts in "Assert.Greater". I get 0 records instead of 2. When I debug the code, the code actually returns the result of the database call, which should be 0 records, not mocked data.

+5
source share
1 answer

unit test :

IUserRepository repo = new UserRepository();

( ASP.NET MVC). , , , unit test, .

/ unit test.

:

public class UserController : Controller
{
    private readonly IUserRepository _repo;
    public UserController(IUserRepository repo)
    {
        _repo = repo;
    }

    public ActionResult Index()
    {
        return RedirectToAction("List");
    }

    public ActionResult List()
    {
        IQueryable<Business.Entities.User> users = _repo.GetAll();
        return View("List", users);
    }
}

unit test :

[Test]
public void List()
{
    Mock<IUserRepository> mockRepo = new Mock<IUserRepository>();
    mockRepo.Setup(ur => ur.GetAll()).Returns(MockedGetAll());
    var v = mockRepo.Object.GetAll();

    var controller = new UserController(mockRepo.Object);
    var result = controller.List() as ViewResult;
    var model = result.ViewData.Model as IQueryable<User>;

    Assert.AreEqual("List", result.ViewName);
    Assert.IsNotNull(model);
    Assert.Greater(model.Count(), 0);
}

, , DI .

, DI, 2 ( ):

private readonly IUserRepository _repo;
public UserController(IUserRepository repo)
{
    _repo = repo;
}

public UserController(): this(new UserRepository())
{

}

, , , , DI.

Haacked .

+15

All Articles