似乎未达到对模拟对象的期望(最小起订量) [英] Expectation on Mock Object doesn't seem to be met (Moq)
问题描述
我在Moq中遇到一些奇怪的行为-尽管事实是我设置了一个模拟对象以某种方式工作,然后以与我正在测试的对象完全相同的方式调用该方法,但它的反应就像该方法从未被调用过.
I'm experiencing some odd behavior in Moq - despite the fact that I setup a mock object to act a certain way, and then call the method in the exact same way in the object I'm testing, it reacts as if the method was never called.
我要测试以下控制器操作:
I have the following controller action that I'm trying to test:
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
类无法使用扩展方法来扩展...叹气...).
where AssertThat
is just a class of my own with a bunch of assertion helpers (since the Assert
class can't be extended with extension methods... sigh...).
运行测试时,它在repository.Verify()
行上失败,并带有MoqVerificationException
:
When I run the test, it fails on the repository.Verify()
line, with a 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
块中.那里没问题.
If I remove repository.Verify()
, the collection assert fails telling me that the model returned is null
. I have debugged and checked that query != null
, and that I am taken into the part of the if
block where the code is run. No problems there.
为什么这行不通?
推荐答案
我怀疑这是因为您要传递到模拟存储库中的数组(teststring.Split(' ')
的结果)与实际获得的对象不是同一对象通过Search方法(query.Split(' ')
的结果)传入.
I suspect it's because the array you're passing into your mocked repository (the result of teststring.Split(' ')
) is not the same object as the one that actually gets passed in from the Search method (the result of query.Split(' ')
).
尝试将安装代码的第一行替换为:
Try replacing the first line of your setup code with:
repository.Expect(r => r.SearchForContacts(
It.Is<String[]>(s => s.SequenceEqual(keywords)), includeAll))
...,它将比较传递给模拟对象的数组的每个元素与keywords
数组中的相应元素.
... which will compare each element of the array passed to your mock with the corresponding element in the keywords
array.
这篇关于似乎未达到对模拟对象的期望(最小起订量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!