我在 Moq 中遇到了一些奇怪的行为 - 尽管我设置了一个模拟对象以某种方式行事,然后在我正在测试的对象中以完全相同的方式调用该方法,但它的反应就像该方法是从来没有打电话过。
我正在尝试测试以下控制器操作:
public ActionResult Search(string query, bool includeAll)
{
if (query != null)
{
var keywords = query.Split(' ');
return View(repo.SearchForContacts(keywords, includeAll));
}
else
{
return View();
}
}
我的单元测试代码:
public void SearchTestMethod() // Arrange
var teststring = "Anders Beata";
var keywords = teststring.Split(' ');
var includeAll = false;
var expectedModel = dummyContacts.Where(c => c.Id == 1 || c.Id == 2);
repository
.Expect(r => r.SearchForContacts(keywords, includeAll))
.Returns(expectedModel)
.Verifiable();
// Act
var result = controller.Search(teststring, includeAll) as ViewResult;
// Assert
repository.Verify();
Assert.IsNotNull(result);
AssertThat.CollectionsAreEqual<Contact>(
expectedModel,
result.ViewData.Model as IEnumerable<Contact>
);
}
where AssertThat
只是我自己的一个类,带有一堆断言助手(因为Assert
类无法使用扩展方法进行扩展...叹息...)。
当我运行测试时,它失败了repository.Verify()
线,用一个MoqVerificationException
:
Test method MemberDatabase.Tests.Controllers.ContactsControllerTest.SearchTestMethod()
threw exception: Moq.MockVerificationException: The following expectations were not met:
IRepository r => r.SearchForContacts(value(System.String[]), False)
如果我删除repository.Verify()
,集合断言失败告诉我返回的模型是null
。我已经调试并检查过query != null
,并且我被纳入了if
代码运行的块。那里没有问题。
为什么这不起作用?