Moq在安装程序具有回调时引发NullReferenceException异常

时间:2018-07-17 13:46:32

标签: c# unit-testing mocking moq assert

我有单元测试。当我为接口功能的设置定义回调函数并在调用时调用Verify时,Moq会抛出NullReferenceException异常,我对此感到非常困惑。

更新: 我忘了提到重要的部分。 当我一一运行测试时,一切正常,但是当我运行所有测试时,此测试失败。

例外:

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

单元测试:

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

PersistActionSet方法的签名是:

void PersistActionSet(string companyId, IList<CsiNotificationActionSet> actionSets)

关于为什么发生这种情况或对指针的任何理解,都非常感谢。

1 个答案:

答案 0 :(得分:0)

对于后代和其他突然陷入奇怪错误的人们。 在测试中设置STAThread属性可以解决问题