我試圖單元測試一些使用實體框架6但在添加實體後加載相關實體時出現問題的Web Api 2控制器。我使用起訂量來創建一個嘲弄的DbContext和DbSet,並增加使用Moq爲Web API加載相關實體使用Moq for Web Api 2控制器測試
public virtual void MarkAsModified<T>(T item) where T : class
{
Entry(item).State = EntityState.Modified;
}
,以繞過_db.Entry(foo).State = EntityState.Modified;
問題上的認沽行動。
在這個簡化的例子中,Api Action是一個Post,我們需要找回2個相關實體(Bar和Qux)。
[ResponseType(typeof (Foo))]
public async Task<IHttpActionResult> PostFoo(Foo foo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//Do other stuff
_db.Foos.Add(foo);
_db.Entry(foo).Reference(x => x.Bar).Load();
_db.Entry(foo).Reference(x => x.Qux).Load();
await _db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new {id = foo.Id},foo);
}
再簡化的測試將是
[TestMethod]
public async Task PostFoo()
{
var model = new Foo
{
Name="New Foo",
QuxId = 99,
Qux = null,
BarId = 66,
Bar = null
};
var result = await _controller.PostFoo(model) as CreatedAtRouteNegotiatedContentResult<Foo>;
Assert.IsNotNull(result);
Assert.IsNotNull(result.Qux);
Assert.IsNotNull(result.Bar);
}
是否有這樣做_db.Entry(foo).Reference(x => x.Bar).Load();