单元测试中的验证失败

时间:2015-02-26 21:35:59

标签: c# .net unit-testing post asp.net-web-api

我正在对PostMyModel路线进行单元测试。但是,在PostMyModel()内,我使用了行Validate<MyModel>(model)来重新验证我的模型。我正在使用测试上下文,以便不依赖于单元测试的数据库。我在下面发布了测试上下文和发布方法:

测试背景

class TestAppContext : APIContextInterface
    {

        public DbSet<MyModel> 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<MyModel>(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<MyModel>(model)行运行时,我收到错误:

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

我该如何纠正?

1 个答案:

答案 0 :(得分:21)

为了运行Validate命令,必须有与控制器关联的模拟HttpRequest。执行此操作的代码如下。这将模拟默认的HttpRequest,在这种情况下它是完全未使用的,允许对方法进行单元测试。

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