Tom*_*han 4 unit-testing moq expect
我在Moq中遇到了一些奇怪的行为 - 尽管事实上我设置了一个模拟对象以某种方式行事,然后在我正在测试的对象中以完全相同的方式调用该方法,它反应就好像方法是从未打电话过
我有以下控制器操作,我正在尝试测试:
public ActionResult Search(string query, bool includeAll)
{
if (query != null)
{
var keywords = query.Split(' ');
return View(repo.SearchForContacts(keywords, includeAll));
}
else
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试代码:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
哪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运行代码的块的一部分.没有问题.
为什么这不起作用?
我怀疑这是因为您传递到模拟存储库的数组(结果teststring.Split(' '))与实际从搜索方法传递的数组(结果query.Split(' '))不同.
尝试用以下代码替换设置代码的第一行:
repository.Expect(r => r.SearchForContacts(
It.Is<String[]>(s => s.SequenceEqual(keywords)), includeAll))
Run Code Online (Sandbox Code Playgroud)
...它将传递给mock的数组的每个元素与数组中的相应元素进行比较keywords.
| 归档时间: |
|
| 查看次数: |
789 次 |
| 最近记录: |