MOQ Error Expected invocation on the mock once, but was 0 times

核能气质少年 提交于 2020-02-03 05:54:59

问题


I am new to MOQ and I have read the Quickstart here. I am using MOQ v4.2.1402.2112. I am trying to create a unit test for updating a person object. The UpdatePerson method returns the updated person object. Can someone tell me how to correct this?

I am getting this error:

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

Here's my code:

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

回答1:


With this line

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

You are setting expectation on mock that UpdatePerson method should be called once. It fails, because your SUT (class you are testing) does not call this method at all:

No invocations performed

Also verify if you pass mocked object to PersonProxy. It should be something like:

PersonProxy = new PersonProxy(PersonMock.Object);

And implementation

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


来源:https://stackoverflow.com/questions/22378286/moq-error-expected-invocation-on-the-mock-once-but-was-0-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!