Moq mock 方法返回null空指针异常
作者:互联网
在使用moq mock方法时如果直接返回null,在方法被调用时会抛出空指针异常
var repository = new Mock<IRepository>();
var someObject = null;
repository.Setup(p => p.GetByIdAsync(It.IsAny<string>()).Result)
.Returns(someObject);
var someObjectFromRepository = await repository.Object.GetByIdAsync("someid");
// 此时会抛出空指针异常
解决方法:
不对改方法进行setup设置,该方法的返回值即为null
var repository = new Mock<IRepository>();
var someObjectFromRepository = await repository.Object.GetByIdAsync("someid");
// 此时someObjectFromRepository为null
标签:someObjectFromRepository,repository,方法,Moq,var,null,GetByIdAsync,mock 来源: https://www.cnblogs.com/Saints/p/14724838.html