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.
source
share