Why Moq is thorwing "expected Invocation on the mock at least once". Where as it is being set once,e

Posted by Mohit on Stack Overflow See other posts from Stack Overflow or by Mohit
Published on 2010-04-05T23:48:17Z Indexed on 2010/04/05 23:53 UTC
Read the original article Hit count: 2813

Filed under:
|
|
|

Following is the code. create a class lib add the ref to NUnit framework 2.5.3.9345 and Moq.dll 4.0.0.0 and paste the following code. Try running it on my machine it throws

TestCase 'MoqTest.TryClassTest.IsMessageNotNull' failed: Moq.MockException : Expected invocation on the mock at least once, but was never performed: v => v.Model = It.Is(value(Moq.It+<>c__DisplayClass21[MoqTest.GenInfo]).match) at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times, Int32 callCount) at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times) at Moq.Mock.VerifySet[T](Mock1 mock, Action1 setterExpression, Times times, String failMessage) at Moq.Mock1.VerifySet(Action`1 setterExpression) Class1.cs(22,0): at MoqTest.TryClassTest.IsMessageNotNull()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Moq;
using NUnit.Framework;

namespace MoqTest
{
    [TestFixture]
    public class TryClassTest
    {
        [Test]
        public void IsMessageNotNull()
        {
            var mockView = new Mock<IView<GenInfo>>();
            mockView.Setup(v => v.ModuleId).Returns("");

            TryPresenter tryPresenter = new TryPresenter(mockView.Object);
            tryPresenter.SetMessage(new object(), new EventArgs());
            // mockView.VerifySet(v => v.Message, Times.AtLeastOnce());
            mockView.VerifySet(v => v.Model = It.Is<GenInfo>(x => x != null));
        }
    }

    public class TryPresenter
    {
        private IView<GenInfo> view;
        public TryPresenter(IView<GenInfo> view)
        {
            this.view = view;
        }

        public void SetMessage(object sender, EventArgs e)
        {
            this.view.Model = null;
        }
    }

    public class MyView : IView<GenInfo>
    {
        #region Implementation of IView<GenInfo>

        public string ModuleId
        {
            get; set;
        }

        public GenInfo Model
        {
            get; set;
        }

        #endregion
    }

    public interface IView<T>
    {
        string ModuleId { get; set; }
        T Model { get; set; }
    }

    public class GenInfo
    {
        public String Message { get; set; }
    }
}

And if you change one line mockView.VerifySet(v => v.Model = It.Is(x => x != null)); to mockView.VerifySet(v => v.Model, Times.AtLeastOnce()); it works fine.

I think Exception is incorrect.

© Stack Overflow or respective owner

Related posts about moq

Related posts about c#