c# - 当类在服务项目中时,最小起订量在不可覆盖的成员上抛出无效设置

标签 c# visual-studio service moq

我正在尝试对此类 ServizioController 进行单元测试:

public class ServizioController : IServizioController
{

    public virtual void PerformAction(Super.Core.Servizio servizio)
    {
    }

    public virtual bool Start()
    { throw new NotImplementedException(); }

    public virtual bool Stop()
    { throw new NotImplementedException(); }

    public virtual bool Continue()
    { throw new NotImplementedException(); }
}

如果这个类是测试或库项目的一部分,那就没问题了。但是当它在服务项目中时,起订量给我这个错误:

Invalid setup on a non-overridable member: x => x.Start()

我的测试是这样的:

[TestMethod]
        public void ServizioController_PerformAction_Start()
        {
            //Arrange
            bool _start, _stop, _continue;
            _start = _stop = _continue = false;


            Super.Core.Servizio s = new Super.Core.Servizio()
            {
                Action = ServizioAction.START.ToString()
            };

            var mock = new Mock<ServizioController>() { CallBase = true };;
            mock.Setup(x => x.Start())
               .Callback(() => _start = true);
            mock.Setup(x => x.Stop())
               .Callback(() => _stop = true);
            mock.Setup(x => x.Continue())
               .Callback(() => _continue = true);

            //Act
            mock.Object.PerformAction(s);

            //Assert
            Assert.IsTrue(_start);
            Assert.IsFalse(_stop);
            Assert.IsFalse(_continue);
        }

我愿意继续,所以这门课将加入图书馆课,但如果有人能向我解释这种行为,我会非常高兴......

谢谢,

最佳答案

您的 Setup 方法需要有一个 Returns,因为您正在模拟的那些方法都返回一个 bool。

mock.Setup(x => x.Start()).Returns(true);

附带说明一下,在这种情况下您不需要使用Callback,因为Verify 会为您完成这项工作

public void ServizioController_PerformAction_Start()
    {
        //Arrange
        Super.Core.Servizio s = new Super.Core.Servizio()
        {
            Action = ServizioAction.START.ToString()
        };

        var mock = new Mock<ServizioController>() { CallBase = true };
        mock.Setup(x => x.Start()).Returns(true);
        mock.Setup(x => x.Stop()).Returns(true);
        mock.Setup(x => x.Continue()).Returns(true);

        //Act
        mock.Object.PerformAction(s);

        //Assert
        mock.Verify(x => x.Start());
        mock.Verify(x => x.Stop());
        mock.Verify(x => x.Continue());
    }

关于c# - 当类在服务项目中时,最小起订量在不可覆盖的成员上抛出无效设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6469283/

相关文章:

c# - 使用 .net MVC RadioButtonFor() 时,如何分组以便只能进行一个选择?

c# - 在 LINQ to SQL 中联接多级关系

android - 通知中的操作不执行任何操作

c# - 使用 PHP SOAP 服务返回一个数组

c# - 根据用户请求在后台生成文件

c# - 类型 'ImageConverter' 存在于两者中

visual-studio - LNK1112 : module machine type 'x64' conflicts with target machine type 'x86' - opencv build

c# - 您如何在 Visual Studio 中管理多个 AWS Lambda 函数?

windows - 以特定用户身份运行 Web 应用程序

c# - 如何编写包含我的 Windows Live ID 的 HttpRequest?