Moq is throwing Invalid setup on a non-overridable

2019-07-04 12:05发布

I am trying to unit test this class 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(); }
}

It goes fine if this class is part of a test or a library project. But When it is in the Service Project, Moq is throwing me this error:

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

My test looks like this :

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

I am willing to continue, so This class is going to join a library class, but if someone could explain me this behavior , I would be more than happy...

thanks,

1条回答
Root(大扎)
2楼-- · 2019-07-04 12:21

Your Setup methods need to have a Returns as those methods you are mocking all return a bool.

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

On a side note, you do not need to use Callback in this instance as Verify will do the job for you

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());
    }
查看更多
登录 后发表回答