验证单元测试失败 [英] Validate fails in unit tests

查看:81
本文介绍了验证单元测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running a unit test of my PostMyModel route. However, within PostMyModel() I used the line Validate<MyModel>(model) to revalidate my model after it is changed. I am using a test context, so as not to be dependent on the db for the unit tests. I have posted the test context and post method below:

测试上下文

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)行运行时,出现错误:

When the Validate<MyModel>(model) line runs, I get the error :

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

我该如何纠正?

推荐答案

为了运行Validate命令,必须有与控制器关联的模拟HttpRequest.下面是执行此操作的代码.这将模拟默认的HttpRequest,在这种情况下该HttpRequest尚未使用,因此可以对该方法进行单元测试.

In order for the Validate command to run, there must be mock HttpRequest associated with the controller. The code to do this is below. This will mock a default HttpRequest, which is fairly unused in this case, allowing the method to be unit tested.

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

这篇关于验证单元测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆