所以,我使用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