在单元测试中模拟 UnitOfWorkManager.Current

Mocking the UnitOfWorkManager.Current in a unit test

单元测试时,系统无法解析UnitOfWorkManager.Current(空引用异常)。 _unitOfWorkManager 的类型为:IUnitOfWorkManager,并通过 DI 注入。

我正在测试以下网络 api 代码:

[HttpPost]
public async Task<IHttpActionResult> Subscription(SubscriptionInputDto model)
{
    if (!await VendorHasAccess(model.OrganizationId))
        return StatusCode(HttpStatusCode.Forbidden);

    var input = new Subscription
    {
        ...
    };

    var data = await _subscriptionRepository.InsertAsync(input);

    await _unitOfWorkManager.Current.SaveChangesAsync();

    return Ok(data.MapTo<SubscriptionDto>());
}

…使用以下单元测试:

[Fact]
public async Task Should_Create_New_Subscription()
{
    //Arrange
    var organization = await UsingDbContextAsync(async context => await context.VendorOrganizations.FirstOrDefaultAsync());
    var input = new SubscriptionInputDto { OrganizationId = organization.Id };

    //Act
    var actionResult = await _vendorController.Subscription(input);
    var response = actionResult as OkNegotiatedContentResult<SubscriptionDto>;

    //Assert
    Assert.NotNull(response);
    Assert.Equal(organization.Id, response.Content.OrganizationId);
}

我无法弄清楚,也找不到任何有关如何解决 UnitOfWorkManager.Current 的文档,以便单元测试不会失败。 Web API 代码本身可以在生产环境中运行。

有什么建议吗?

创建控制器方法virtual

参见:UnitOfWork Attribute Restrictions

You can use UnitOfWork attribute for:

  • All public virtual methods for self injected classes (Like MVC Controllers and Web API Controllers).

更新

如果在您的测试中明确开始一个工作单元是一个合理的解决方案:

using (var unitOfWork = Resolve<IUnitOfWorkManager>().Begin())
{
    // ...
    unitOfWork.Complete();
}