如何在带有XUnit的ASP.NET Core中测试具有依赖项注入的控制器?

时间:2018-06-22 10:31:29

标签: c# asp.net-core xunit

我正在编写我的ASP.NET Core Web API,我想开始用XUnit编写单元测试(我知道,这样做有些迟了,但是嘿,总比没有好。),但是我有点依赖注射在这里。这是我的示例 Controller 类:

public class UnitController : MyController {

  private readonly MyContext _context;

  public UnitController(MyContext context) {
    _context = context;
  }
}

MyContext 类:

  public class MyContext : DbContext {
    private readonly IHttpContextAccessor _httpContext;

    public MyContext(DbContextOptions options, IHttpContextAccessor httpContext) : base(options) {
      _httpContext = httpContext;
    }
  }

以及 Startup.cs 中的 ConfigureServices 方法:

public void ConfigureServices(IServiceCollection services) {
  services.AddDbContext<MyContext>(options => options.UseMySql(Configuration.GetConnectionString("MyContext"))
    .ConfigureWarnings(warnings => warnings.Ignore(RelationalEventId.QueryClientEvaluationWarning)));
  services.AddHttpContextAccessor();
  services.AddMvc();
}

还有我可怜的XUnit类:

  public class UnitControllerTest {
    private readonly MyContext _context;

    public UnitControllerTest() {
      var configuration = new Mock<IConfiguration>().Object;
      var dbOptions = new DbContextOptionsBuilder().UseMySql(configuration.GetConnectionString("MyContext"));
      _context = new Mock<MyContext>(dbOptions).Object;
    }

    [Fact]
    public void AddUnit_InvalidModel_ShouldReturnBadRequest() {
      var controller = new UnitController(_context);
      var testUnit = new Unit();
      var result = controller.AddUnit(testUnit);

      Assert.Equal(typeof(BadRequestObjectResult), result.GetType());
    }   
  }

我的问题是,

如何正确编写测试?

0 个答案:

没有答案