MOQ错误模拟一次的预期调用,但是是0次

Que*_*Que 5 unit-testing moq

我是MOQ的新手,我在这里阅读了快速入门.我使用的是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
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

    [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.");
    }
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 10

有了这条线

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

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

没有进行任何调用

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

PersonProxy = new PersonProxy(PersonMock.Object);
Run Code Online (Sandbox Code Playgroud)

并实施

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);
    }
}
Run Code Online (Sandbox Code Playgroud)