我在 Moq 中遇到了一些奇怪的行为 - 尽管我设置了一个模拟对象以某种方式行事,然后在我正在测试的对象中以完全相同的方式调用该方法,但它的 react 好像该方法是从来没有叫过。
我正在尝试测试以下 Controller 操作:
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>
);
}
哪里
AssertThat
只是我自己的一个带有一堆断言助手的类(因为 Assert
类不能用扩展方法扩展......叹气......)。当我运行测试时,它在
repository.Verify()
上失败了线,带有 MoqVerificationException
:测试方法 MemberDatabase.Tests.Controllers.ContactsControllerTest.SearchTestMethod()
抛出异常:Moq.MockVerificationException:未满足以下期望:
IRepository r => r.SearchForContacts(value(System.String[]), False)
如果我删除
repository.Verify()
,集合断言失败告诉我返回的模型是 null
.我已经调试并检查了 query != null
,我被带入了if
的一部分代码运行的块。那里没有问题。为什么这不起作用?
最佳答案
我怀疑这是因为您传递到模拟存储库中的数组( teststring.Split(' ')
的结果)与实际从 Search 方法( query.Split(' ')
的结果)传入的对象不同。
尝试将设置代码的第一行替换为:
repository.Expect(r => r.SearchForContacts(
It.Is<String[]>(s => s.SequenceEqual(keywords)), includeAll))
... 将传递给模拟的数组的每个元素与
keywords
中的相应元素进行比较大批。
关于unit-testing - 对 Mock Object 的期望似乎没有得到满足(Moq),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1220013/