简体   繁体   English

如何调试此或可能的原因? Moq.Verify上的用户代码未处理System.NullReferenceException

[英]How to debug this or possible causes? System.NullReferenceException was unhandled by user code on Moq.Verify

I have something like this in my unit test 我的单元测试中有类似的内容

public class MyTestClass()
{
      private Mock<IAccountRepo> accountRepo;
       private AdminService adminService;

      [Setup]
      public void Setup()
      {
        accountRepo = fixture.Freeze<Mock<IAccountRepo>>();
        adminService = fixture.CreateAnonymous<AdminService>();
      }

      [Test]
      public Test()
      {
          accountRepo.Setup(x => x.Insert(It.IsAny<IUnitOfWork>(), It.IsAny<MyDomainObject>()));

            adminService.ApplyAdminFee(1, 1, today);

            accountRepo.Verify(x => x.Insert(It.IsAny<IUnitOfWork>(), It.Is<MyDomainObject>(a => a.Id == 1)));
      }
}

I get this error. 我得到这个错误。

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at lambda_method(Closure , MyDomainObject )
       at Moq.It.<>c__DisplayClass2`1.<Is>b__1(TValue value)
       at Moq.Match`1.Matches(Object value)
       at Moq.Matcher.Matches(Object value)
       at Moq.MethodCall.Matches(IInvocation call)
       at Moq.Mock.<>c__DisplayClassc.<VerifyCalls>b__b(IInvocation i)
       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 Test() in 383
  InnerException: 

I am not sure why. 我不知道为什么。

Edit 编辑

I think I know what is happening. 我想我知道发生了什么事。 in my method I have 3 calls to the insert method(the insert method takes in an object). 在我的方法中,我对insert方法有3次调用(insert方法接受一个对象)。

So I have like 所以我喜欢

accountRepo.Insert(MyDomainObject);
accountRepo.Insert(MyOtherDomainObject);
accountRepo.Insert(MyOtherOtherDomainObject);

So maybe those 2 other inserts are overriding it? 那么,也许其他2个插入内容都覆盖了它? how can I get around this? 我该如何解决?

The problem is in here: It.Is<MyDomainObject>(a => a.Id == 1) . 问题在这里: It.Is<MyDomainObject>(a => a.Id == 1) You can tell from the stack trace. 您可以从堆栈跟踪中看出。

I would change it like this: It.Is<MyDomainObject>(a => a != null && a.Id == 1) 我会这样更改: It.Is<MyDomainObject>(a => a != null && a.Id == 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM