在使用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