我有一个单元测试。当我定义回调函数来设置我的接口函数并调用调用时,调用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)
任何想法为什么发生或指针非常感激。
后人和其他人突然遇到奇怪的错误。在测试中设置STAThread属性解决了问题