Reputation: 13
When unit testing, the system cannot resolve UnitOfWorkManager.Current
(nullreference exception). The _unitOfWorkManager
is of type: IUnitOfWorkManager
, and injected via DI.
I'm testing the following web api code:
[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>());
}
…with the following unit test:
[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);
}
I cannot figure out, or find any documentation on, how to resolve the UnitOfWorkManager.Current
so that it doesn't fail for the unit test.
The web API code itself works in production.
Any tips?
Upvotes: 1
Views: 905
Reputation: 43108
Make your controller method virtual
.
See: UnitOfWork Attribute Restrictions
You can use UnitOfWork attribute for:
- All public virtual methods for self injected classes (Like MVC Controllers and Web API Controllers).
Update
If beginning a unit of work explicitly in your test is a reasonable resolution:
using (var unitOfWork = Resolve<IUnitOfWorkManager>().Begin())
{
// ...
unitOfWork.Complete();
}
Upvotes: 2