单元测试- MOQ错误期望在模拟上调用一次,但是调用了0次



我是最小起订量的新手,我已经在这里阅读了快速入门。我正在使用最小起订量v4.2.1402.2112。我试图创建一个更新人对象的单元测试。UpdatePerson方法返回更新后的person对象。有人能告诉我怎么改正吗?

我得到这个错误:

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.");
    }

一行

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

您正在mock上设置期望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);
    }
}

相关内容

  • 没有找到相关文章

最新更新