我想要模拟惰性接口,但我得到了object reference not set to an instance of an object
例外。
这是正在测试的类:
public class ProductServiceService : IProductServiceService
{
private readonly Lazy<IProductServiceRepository> _productServiceRepository;
private readonly Lazy<IProductPackageRepository> _productPackageRepository;
public ProductServiceService(
Lazy<IProductServiceRepository> productServiceRepository,
Lazy<IProductPackageRepository> productPackageRepository)
{
_productServiceRepository = productServiceRepository;
_productPackageRepository = productPackageRepository;
}
public async Task<OperationResult> ValidateServiceAsync(ProductServiceEntity service)
{
var errors = new List<ValidationResult>();
if (!await _productPackageRepository.Value.AnyAsync(p => p.Id == service.PackageId))
errors.Add(new ValidationResult(string.Format(NameMessageResource.NotFoundError, NameMessageResource.ProductPackage)));
.
.
.
return errors.Any()
? OperationResult.Failed(errors.ToArray())
: OperationResult.Success();
}
}
这是测试课
[Fact, Trait("Category", "Product")]
public async Task Create_Service_With_Null_Financial_ContactPerson_Should_Fail()
{
// Arrange
var entity = ObjectFactory.Service.CreateService(packageId: 1);
var mockProductServiceRepository = new Mock<Lazy<IProductServiceRepository>>();
var repo = new Mock<IProductPackageRepository>();
repo.Setup(r => r.AnyAsync(It.IsAny<Expression<Func<ProductPackageEntity, bool>>>()));
var mockProductPackageRepository = new Lazy<IProductPackageRepository>(() => repo.Object);
var sut = new ProductServiceService(mockProductServiceRepository.Object, mockProductPackageRepository);
// Act
var result = await sut.AddServiceAsync(service);
// Assert
Assert.False(result.Succeeded);
Assert.Contains(result.ErrorMessages, error => error.Contains(string.Format(NameMessageResource.NotFoundError, NameMessageResource.ProductPackage)));
}
mockProductPackageRepository
始终为空。我关注了这篇博文,但仍然遇到空引用异常。
如何使用 Moq 在 C# 单元测试中模拟对象的延迟初始化
Update:
here is a screen that indicates fakeProductPackageRepository
is null.