我在我的ASP.NET MVC应用程序中的“UserController”中有以下代码:
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);
}
}
使用 Moq,我想模拟数据库调用 "repo.GetAll()"。下面是我的测试代码:
[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);
}
我有一个函数,可以返回一些静态数据来满足测试需求:
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();
}
测试在“Assert.Greater”处中断。 我获得了0个记录而不是2个。 当我调试代码时,实际上返回的是数据库调用的结果,这应该是0个记录,而不是模拟数据。