-->

关于Mock对象的预期似乎并没有得到满足(MOQ)(Expectation on Mock Obje

2019-09-21 23:02发布

我遇到的起订量一些奇怪的行为 - 尽管事实上,我设置一个模拟对象采取行动以某种方式,然后调用在我测试的对象完全相同的方式方法,扛起如果方法从来没有所谓。

我有我想测试下的控制器操作:

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

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其中运行代码块。 没有问题存在。

为什么没有这方面的工作?

Answer 1:

我怀疑这是因为,您将进入你的嘲弄库(结果数组teststring.Split(' ')是不相同的对象实际上从搜索方法(的结果传递的一个query.Split(' ')

尝试更换与您的设置代码的第一行:

repository.Expect(r => r.SearchForContacts(
    It.Is<String[]>(s => s.SequenceEqual(keywords)), includeAll))

...这会比较传递给你的模拟与相应元素阵列中的每个元素keywords阵列。



文章来源: Expectation on Mock Object doesn't seem to be met (Moq)