mardi 29 décembre 2015

Loading Related Entities in Mocked DbContext using Moq for Web Api 2 Controller Tests

I'm trying to unit test some Web Api 2 Controllers that use Entity Framework 6 but having issues with the loading of the related entities after the entity has been added. I'm using Moq to create a mocked DbContext and DbSet, and have added

public virtual void MarkAsModified<T>(T item) where T : class
{
   Entry(item).State = EntityState.Modified;
}

to get around the _db.Entry(foo).State = EntityState.Modified; issue on a Put action.

The Api Action is a Post in this simplified example where we need to get back 2 related entities (Bar and 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);
}

And then a simplified test would be

[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);
}

Is there a more mock-friendly way of doing _db.Entry(foo).Reference(x => x.Bar).Load();

Aucun commentaire:

Enregistrer un commentaire