SetupSet/VerifySet 起订量失败

Moq failed for SetupSet/VerifySet

我是 Moq 的新手,我有这个测试功能:

using Moq;
using Xunit;

namespace MyTest
{
    public class UseMoq
    {
        public interface IFoo
        {
            string Name { get; set; }
        }
        [Fact]
        public static void UseMock()
        {
            var mock = new Mock<IFoo>();
            mock.SetupSet(foo => foo.Name = "foo");
            mock.VerifySet(foo => foo.Name = "foo");
        }
    }
}

它运行失败,说:

Message: 
    Moq.MockException : 
    Expected invocation on the mock at least once, but was never performed: foo => foo.Name = "foo"

    Performed invocations:

    Mock<UseMoq.IFoo:1> (foo):
    No invocations performed.

Stack Trace: 
    Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
    Mock.VerifySet(Mock mock, LambdaExpression expression, Times times, String failMessage)
    Mock`1.VerifySet(Action`1 setterExpression)
    ... ...

此错误消息的实际含义是什么,如何解决?

失败是因为您没有实现,要测试 属性 值中的更改,您必须通过实现而不是接口

来更改它

也许这个例子对你有帮助

public class UseMoq
{
    public interface IFoo
    {
        string Name { get; set; }
    }

    public class Foo : IFoo
    {
        private readonly IFoo _foo;

        public Foo(IFoo foo)
        {
            _foo = foo;
        }

        public string Name { get; set; }

        public string GetName()
        {
            return _foo.Name;
        }

        public void SetName(string name)
        {
            _foo.Name = name;
        }
    }

    [Fact]
    public static void UseMock()
    {
        var mock = new Mock<IFoo>();
        mock.SetupGet(x => x.Name).Returns("foo");

        var fooName = new Foo(mock.Object).GetName();

        mock.VerifyGet(m => m.Name, Times.Once);



        /*
         * Another TestMethod

         */

        new Foo(mock.Object).SetName("new Foo Name");

        mock.VerifySet(m => m.Name = "new Foo Name",Times.Once);

    }
}

模拟框架按设计运行。

您正在对尚未调用的模拟成员调用验证。这就是为什么您在所示示例中出现错误的原因。

mock.SetupSet(foo => foo.Name = "foo"); //<--Setup expectation
mock.VerifySet(foo => foo.Name = "foo"); //<--Verify expectation

因为设置告诉模拟框架期望某些行为但是

No invocations performed.

如失败消息所述

Expected invocation on the mock at least once, but was never performed: foo => foo.Name = "foo"

也就是说,Verify* 方法通常在测试用例的 Assert 阶段调用。到那时,模拟将被某些被测对象用作依赖项,并且模拟成员在执行被测对象时按预期调用。

//Arrange

//...initialize mock...

mock.SetupSet(foo => foo.Name = "foo"); //<--Setup expectation

//Act
//...subject under test uses mock

//Assert
mock.VerifySet(foo => foo.Name = "foo"); //<--Verify expectation

查看 MOQ Quickstart: Verification 以获得更多示例。