gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:24:19 25 4
gpt4 key购买 nike

我的单元测试中有这样的东西

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

我收到这个错误。

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:

我不知道为什么。

编辑

我想我知道发生了什么。在我的方法中,我调用了 3 次插入方法(插入方法接受一个对象)。

所以我喜欢

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

所以也许其他 2 个插入内容覆盖了它?我该如何解决这个问题?

最佳答案

问题出在这里:It.Is<MyDomainObject>(a => a.Id == 1) .您可以从堆栈跟踪中看出。

我会这样改:It.Is<MyDomainObject>(a => a != null && a.Id == 1)

关于c# - 如何调试这个或可能的原因? Moq.Verify 上的用户代码未处理 System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13185385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com