Why Moq is throwing "expected Invocation on the mock at least once". Where as it is being set once,even though it is being set to null?
You are using the following VerifySet assertion:
mockView.VerifySet(v => v.Model = It.Is<GenInfo>(x => x != null));
which basically says "verify that I Set the Model property with some GenInfo object that's not null".
Then, you set the Model property with a null object:
this.view.Model = null;
Of course the assertion fails.
In your second VerifySet assertion
mockView.VerifySet(v => v.Model, Times.AtLeastOnce());
you are saying "assert that the Model property was Set, with anything, at least once". Since you did Set it (albeit with a null), of course the assertion passes.
I don't think there's any error in Moq's behavior here.
Mohit
Updated on June 13, 2022Comments
-
Mohit almost 2 years
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)
1 mock,
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](Mock
Action1 setterExpression, Times
1.VerifySet(Action`1
times, String failMessage) at
Moq.Mock
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<GenInfo>(x => x != null));
to
mockView.VerifySet(v => v.Model, Times.AtLeastOnce());
it works fine.
I think Exception is incorrect.