Moq throws NullReferenceException exception when setup has a callback
I have a unit test. When I define call back function for the setup of my function of the interface and call Verify on the call Moq throws NullReferenceException
exception that I am really puzzled by.
Update: I forgot to mention important part. When I run tests one by one all works fine but when I run all the tests this test fails.
Exception:
System.NullReferenceException : Object reference not set to an instance of an object.
at Moq.MethodCall.Matches(ICallContext call)
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify[T](Mock mock, Expression`1 expression, Times times, String failMessage)
at Moq.Mock`1.Verify(Expression`1 expression, Times times)
at LimitTest.LimitEditor.LimitEditorTest.EditActionSetExistingLimit(Boolean add) in
Unit test:
var io= new Mock<ILimitServiceIO>(MockBehavior.Strict);
var LimitServiceIO= new MemoryLimitServiceIO();
... different setups...
io.Setup(x => x.PersistActionSet(It.Is<string>(id=>id==companyId), It.IsAny<IList<CsiNotificationActionSet>>()))
.Callback((string compid, IList<CsiNotificationActionSet> sets) =>LimitServiceIO.PersistActionSet(compid, sets));
... Do some actions...
//This line throws exception
mockIo.Verify(x => x.PersistActionSet(measure.CompanyId,
It.IsAny<IList<CsiNotificationActionSet>>()), Times.Once());
Assert.AreEqual(2,LimitServiceIO.ActionSets.First(acs => acs.Id == ACTION_SET_A1).Actions.Count,
"Number of Actions does not match");
The signature of PersistActionSet
method is:
void PersistActionSet(string companyId, IList<CsiNotificationActionSet> actionSets)
Any ideas why it happens or pointers are appreciated very much.
Also posting for posterity since I've had this problem a few times as well now, and none of the results from Google solve the issue for me.
If we have a mock object of some class with a method public string Foo(string s)
and we want to do something with the parameter passed to this method, all of the results I have found say you need to use a callback like this:
mockObject.Setup(m => m.Foo(It.IsAny<string>()))
.Callback<string>((s) => { /* Do something with parameter s */ });
but that gives a NullReferenceException. What solves the problem for me is adding a Returns()
before the Callback()
:
mockObject.Setup(m => m.Foo(It.IsAny<string>()))
.Returns("bar")
.Callback<string>((s) => { /* Do something with parameter s */ });