My goal is to unit test the PUT action in an OData v4 controller.
I'm using MOQ for the Entity Framework 6 Context and NBuilder to build out the test data.
I am able to successfully test Get and Get(Id), but am unable to run asserts when I retrieve the HTTPActionResult from the PUT action.
I can see the HTTPActionResult returning an UpdatedODataResult object with an Entity property in debug mode, but I don't see a way to work with it at design time.
Does anyone know how to extract the returned Entity from the Async PUT action response?
Here is the code:
using Models;
using WebApp.DAL;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
namespace WebApp.Controllers.Api
{
public class OrgsController : ODataController
{
private IWebAppDbContext db = new WebAppDbContext();
public OrgsController()
{
}
public OrgsController(IWebAppDbContext Context)
{
db = Context;
}
public async Task<IHttpActionResult> Put([FromODataUri] long Key, Org Entity)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (Key != Entity.Id)
{
return BadRequest();
}
db.MarkAsModified(Entity);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EntityExists(Key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(Entity);
}
//...other actions omitted
}
}
Here is my Unit Test code
[Theory, InlineData(5)]
public async Task Api_Put_Updates_Properties(long Id)
{
//arrange
var mockedDbContext = MocksFactory.GetMockContext<WebAppDbContext>();
mockedDbContext.Object.Orgs.AddRange(MocksFactory.GetMockData<Org>(10));
OrgsController _sut = new OrgsController(mockedDbContext.Object);
Org beforeEntity = new Org
{
Id = Id,
Name = "Put Org",
TaxCountryCode = "PutUs",
TaxNumber = "PutUs01"
};
//act
IHttpActionResult actionResult = await _sut.Put(Id, beforeEntity);
//assert
Assert.NotNull(actionResult);
//Assert.NotNull(actionResult.Entity);
//Assert.Equal(Id, actionResult.Entity.Id);
//Assert.Equal("Put Org", actionResult.Entity.Name);
}