我的目标是在 OData v4 控制器中对 PUT 操作进行单元测试。
我正在为 Entity Framework 6 Context 和 NBuilder 使用 MOQ 来构建测试数据。
我能够成功测试 Get 和 Get(Id),但是当我从 PUT 操作中检索 HTTPActionResult 时无法运行断言。
我可以看到 HTTPActionResult 在调试模式下返回带有 Entity 属性的 UpdatedODataResult 对象,但我看不到在设计时使用它的方法。
有谁知道如何从 Async PUT 操作响应中提取返回的实体?
这是代码:
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
}
}
这是我的单元测试代码
[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);
}