MOQ错误预期对模拟调用一次,但为0次 [英] MOQ Error Expected invocation on the mock once, but was 0 times

查看:73
本文介绍了MOQ错误预期对模拟调用一次,但为0次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是最小起订量的新手,并且已经在此处阅读了快速入门.我正在使用MOQ v4.2.1402.2112.我正在尝试创建用于更新人员对象的单元测试. UpdatePerson方法返回更新的人员对象.有人可以告诉我如何解决这个问题吗?

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?

我收到此错误:

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

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

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

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

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

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

这篇关于MOQ错误预期对模拟调用一次,但为0次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆