所以,我使用moq进行测试,但遇到了阻止我正确模拟的问题,至少我认为是这样。 这是我的仓库类:MOQ问题 - 模拟类返回不正确的数据
public interface IAccountsRepository
{
IQueryable<Account> Accounts { get; }
IQueryable<Account> AccountsPaged(int pageSize, int selectedPage);
}
这是实现的一个(假):
public class FakeAccountsRepository : IAccountsRepository
{
private static readonly IQueryable<Account> FakeAccounts = new List<Account> {
new Account {RegistrationEmail = "[email protected]"},
new Account {RegistrationEmail = "[email protected]"},
new Account {RegistrationEmail = "[email protected]"},
new Account {RegistrationEmail = "[email protected]"},
new Account {RegistrationEmail = "[email protected]"}
}.AsQueryable();
public IQueryable<Account> Accounts
{
get { return FakeAccounts; }
}
public IQueryable<Account> AccountsPaged(int pageSize, int selectedPage)
{
return FakeAccounts.Skip((selectedPage - 1)*pageSize).Take(pageSize).AsQueryable();
}
}
这是一个控制器定义,与真正的网页和假冒或SQL数据完美的作品(IOC)一个真正的web页面内:
public class AccountsController : Controller
{
private IAccountsRepository _accountsRepository;
public int PageSize = 3;
public AccountsController(IAccountsRepository accountsRepository)
{
this._accountsRepository = accountsRepository;
}
public ViewResult List(int selectedPage)
{
return View(_accountsRepository.AccountsPaged(PageSize, selectedPage).ToList());
}
}
这是一个方法,起订量:
static IAccountsRepository MockAccountsRepository(params Account[] accs)
{
// Generate an implementor of IAccountsRepository at runtime using Moq
var mockProductsRepos = new Moq.Mock<IAccountsRepository>();
mockProductsRepos.Setup(x => x.Accounts).Returns(accs.AsQueryable());
return mockProductsRepos.Object;
}
它正常工作与此List实现分页的:
public ViewResult List(int selectedPage)
{
return View(_accountsRepository.Accounts.Skip((selectedPage - 1) * PageSize).Take(PageSize).ToList());
}
但使用这种失败时:
public ViewResult List(int selectedPage)
{
return View(_accountsRepository.AccountsPaged(PageSize, selectedPage).ToList());
}
在不改变测试和不断变化的只有List实现(仅适用于.Accounts做分页)它一切正常,但是当我尝试使用AccountsPaged方法时,它失败返回没有元素。 在实际使用中,在网页上,它可以同时工作。
请指教,谢谢。
编辑: 如果我这样做:
mockProductsRepos.Setup(x => x.AccountsPaged(Moq.It.IsAny<int>(), Moq.It.IsAny<int>())).Returns(accs.AsQueryable());
我获得5项返回而不是2
我现在已经设置了它,就像我已经添加到上面的帖子,但它给了我5项而不是2 - 如果.List()调用正常工作,这将是预期的。我不知道它怎么可能,为什么它会返回正式成员?有没有办法逐步调试moq设置? – BuzzBubba 2009-08-09 10:40:10