当类在Service Project中时,Moq会在不可覆盖的成员上抛出无效设置

时间:2011-06-24 14:31:01

标签: 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(); }
}

如果此类是测试或库项目的一部分,那就没问题了。但当它在服务项目中时,Moq正在向我抛出这个错误:

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

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

感谢,

1 个答案:

答案 0 :(得分:0)

您的Setup方法需要Returns,因为您正在嘲笑的那些方法都会返回一个布尔值。

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