validation在unit testing中失败

我正在运行PostMyModel路线的unit testing。 但是,在PostMyModel()我使用了行Validate(model)来更改模型后重新validation我的模型。 我正在使用测试上下文,以便不依赖于unit testing的数据库。 我在下面发布了测试上下文和post方法:

测试环境

 class TestAppContext : APIContextInterface { public DbSet MyModel { get; set; } public TestAppContext() { this.MyModels = new TestMyModelDbSet(); } public int SaveChanges(){ return 0; } public void MarkAsModified(Object item) { } public void Dispose() { } } 

发布方法

 [Route(""), ResponseType(typeof(MyModel))] public IHttpActionResult PostMyModel(MyModel model) { //Save model in DB model.status = "Waiting"; ModelState.Clear(); Validate(model); if (!ModelState.IsValid) { return BadRequest(ModelState); } db.MyModels.Add(model); try { db.SaveChanges(); } catch (DbUpdateException) { if (MyModelExists(model.id)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DisplayMyModel", new { id = model.id }, model); } 

Validate(model)行运行时,我收到错误:

 System.InvalidOperationException: ApiController.Configuration must not be null. 

我怎么能纠正这个?

为了运行Validate命令,必须存在与控制器关联的模拟HttpRequest。 执行此操作的代码如下。 这将模拟默认的HttpRequest,在这种情况下相当未使用,允许对方法进行unit testing。

  HttpConfiguration configuration = new HttpConfiguration(); HttpRequestMessage request = new HttpRequestMessage(); controller.Request = request; controller.Request.Properties["MS_HttpConfiguration"] = configuration;