【问题标题】:MOQ Error Expected invocation on the mock once, but was 0 timesMOQ 错误预期在模拟上调用一次,但为 0 次
【发布时间】:2014-03-13 12:11:54
【问题描述】:

我是 MOQ 的新手,我已阅读快速入门 here。我正在使用 MOQ v4.2.1402.2112。我正在尝试创建一个用于更新人员对象的单元测试。 UpdatePerson 方法返回更新后的人员对象。谁能告诉我如何纠正这个问题?

我收到此错误:

Moq.MockException was unhandled by user code 
HResult=-2146233088
Message=Error updating Person object
Expected invocation on the mock once, but was 0 times: svc => svc.UpdatePerson(.expected)
Configured setups: svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Never
No invocations performed.
  Source=Moq
  IsVerificationError=true

这是我的代码:

    [TestMethod]
    public void UpdatePersonTest()
    {
        var expected = new Person()
        {
            PersonId = new Guid("some guid value"),
            FirstName = "dev",
            LastName = "test update",
            UserName = "dev@test.com",
            Password = "password",
            Salt = "6519",
            Status = (int)StatusTypes.Active
        };

        PersonMock.Setup(svc => svc.UpdatePerson(It.IsAny<Person>())) 
            .Returns(expected) 
            .Verifiable();

        var actual = PersonProxy.UpdatePerson(expected);

        PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()), Times.Once(), "Error updating Person object");

        Assert.AreEqual(expected, actual, "Not the same.");
    }

【问题讨论】:

  • 向我们展示您正在测试的方法。

标签: unit-testing moq


【解决方案1】:

用这条线

PersonMock.Verify(svc => svc.UpdatePerson(It.IsAny<Person>()), 
                  Times.Once(), // here
                  "Error updating Person object");

您正在对模拟设置期望 UpdatePerson 方法应该被调用一次。它失败了,因为您的 SUT(您正在测试的类)根本没有调用此方法:

未执行任何调用

还要验证您是否将模拟对象传递给PersonProxy。它应该是这样的:

PersonProxy = new PersonProxy(PersonMock.Object);

及实施

public class PersonProxy
{
    private IPersonService service; // assume you are mocking this interface

    public PersonProxy(IPersonService service) // constructor injection
    {
        this.service = service;
    }

    public Person UpdatePerson(Person person)
    {
         return service.UpdatePerson(person);
    }
}

【讨论】:

  • 感谢您的详细解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
相关资源
最近更新 更多