使用MoqforWebApi2控制器测试在模拟DbContext中加载相关实体

本文关键字:加载 实体 DbContext 模拟 MoqforWebApi2 控制器 测试 使用 | 更新日期: 2023-09-27 18:28:21

我正在尝试对一些使用Entity Framework 6的Web Api 2控制器进行单元测试,但在添加实体后加载相关实体时遇到问题。我正在使用Moq创建一个模拟的DbContext和DbSet,并添加了

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

以绕过Put操作中的_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();

使用MoqforWebApi2控制器测试在模拟DbContext中加载相关实体

关于解决方案的总体想法可以在这里看到

单元测试ASP.NET Web API 2时的模拟实体框架:依赖项注入

目前,您的控制器与EF的耦合过于紧密,因此我的建议是将DbContext和DbSet依赖关系从控制器中抽象出来,这样它就可以变得对mock友好。

为了绕过_db.Entry(foo).Reference(x => x.Bar).Load(),这里有一个基于您在后中使用的相关操作的简化抽象

public interface IUnitOfWork {
    void Add<T>(T item) where T : class;
    void MarkAsModified<T>(T item) where T : class;
    void LoadRelatedEntity<T, TRelated>(T item, Expression<Func<T, TRelated>> exp)
        where T : class
        where TRelated : class;
    Task SaveChangesAsync();
}

并允许具体实现能够做到这一点。

public void LoadRelatedEntity<T, TRelated>(T item, Expression<Func<T, TRelated>> exp) 
    where T : class
    where TRelated : class
{
    _db.Entry(item).Reference(exp).Load();
}

这种依赖关系现在可以被注入到控制器中,也可以被模拟。

以下是潜在控制器的简化版本

public class FooController : ApiController {
    IUnitOfWork unitOfWork;
    public FooController (IUnitOfWork uow) {
        this.unitOfWork = uow;
    }
    [ResponseType(typeof(Foo))]
    public async Task<IHttpActionResult> PostFoo(Foo foo) {
        if (!ModelState.IsValid) {
            return BadRequest(ModelState);
        }
        //Do other stuff
        unitOfWork.Add(foo);
        await unitOfWork.SaveChangesAsync();
        //Load related entities
        unitOfWork.LoadRelatedEntity(foo, x => x.Bar);
        unitOfWork.LoadRelatedEntity(foo, x => x.Qux);
        return CreatedAtRoute("DefaultApi", new { id = foo.Id }, foo);
    }
}

从那里开始,这只是一个创建测试的问题。

[TestMethod]
public async Task TestPostFoo() {
    //Arrange
    bool saved = false;
    var model = new Foo {
        Name = "New Foo",
        QuxId = 99,
        Qux = null,
        BarId = 66,
        Bar = null
    };
    var mockUnitOfWork = new Moq.Mock<IUnitOfWork>();
    mockUnitOfWork.Setup(x => x.SaveChangesAsync())
        .Returns(() => Task.FromResult(0))
        .Callback(() => {
            model.Id = 1;
            saved = true;
        });
    mockUnitOfWork
        .Setup(x => x.LoadRelatedEntity<Foo, Qux>(It.IsAny<Foo>(), It.IsAny<Expression<Func<Foo, Qux>>>()))
        .Callback(() => model.Qux = new Qux());
    mockUnitOfWork
        .Setup(x => x.LoadRelatedEntity<Foo, Bar>(It.IsAny<Foo>(), It.IsAny<Expression<Func<Foo, Bar>>>()))
        .Callback(() => model.Bar = new Bar());
    var controller = new TestsFooApiController(mockUnitOfWork.Object);
    controller.Request = new HttpRequestMessage { };
    controller.Configuration = new HttpConfiguration();
    //Act
    var result = await controller.PostFoo(model) as CreatedAtRouteNegotiatedContentResult<Foo>;
    //Assert
    result.Should().NotBeNull();
    result.Content.Should().NotBeNull();
    result.Content.Id.Should().BeGreaterThan(0);
    result.Content.Qux.Should().NotBeNull();
    result.Content.Bar.Should().NotBeNull();
    saved.Should().BeTrue();
}

希望这能帮助