WebApi Controller create action方法在前端应用程序上工作正常,但在单元测试Request上为null

时间:2016-01-15 19:50:36

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

我有以下控制器操作

// POST api/TiposDeCanal   add
        public HttpResponseMessage PostTipoDeCanal(TipoDeCanal tipoDeCanal)
        {
            if (ModelState.IsValid)
            {
                unitOfWork.TipoDeCanalRepository.Insert(tipoDeCanal);
                unitOfWork.Save();

                DataSourceResult result = new DataSourceResult
                {
                    Data = new[] { tipoDeCanal },
                    Total = 1
                };
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, result);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = tipoDeCanal.ID}));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

我的观点是使用telerik控件,效果非常好

@model List<PowerData.Comisiones.Models.TipoDeCanal>
@using PowerData.Comisiones.Models
@{
    ViewBag.Title = "Tipos de Canal";
}

<h2>Tipos de Canal</h2>

@(Html.Kendo().Grid<TipoDeCanal>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Nombre).Title("Nombre");
        columns.Bound(p => p.Descripcion).Title("Descripcion");
        columns.Command(command => { command.Edit(); command.Destroy(); });
    })
    .ToolBar(toolbar => toolbar.Create())   
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable()
    .Sortable()
    .Scrollable(scr => scr.Height(430))
    .Filterable()  
    .DataSource(dataSource => dataSource
        .WebApi()
        //.Ajax()
        //.ServerOperation(false)
        .PageSize(20)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Id(p => p.ID);
            model.Field(p => p.ID).Editable(false);
        })
        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales" }))) // Action invoked when the user saves a new data item
            .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales" }))) // Action invoked when the grid needs data
            .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales", id = "{0}" })))  // Action invoked when the user saves an updated data item
            .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "TipoDeCanales", id = "{0}" }))) // Action invoked when the user removes a data item

        //.Create(update => update.Action("Create", "TipoDeCanales"))
        //.Read(read => read.Action("Read", "TipoDeCanales"))
        //.Update(update => update.Action("Edit", "TipoDeCanales"))
        //.Destroy(update => update.Action("Delete", "TipoDeCanales"))
    )
)
<script type="text/javascript">
    function error_handler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            toastr.error(message)
            //alert(message);
        }
    }
</script>

上面的代码在浏览器上运行得很好,但单元测试在Request.CreateResponse行上失败,因为请求对象为null。

[TestClass]
    public class TipoDeCanalesControllerTest: GenericApiController
    {
        [TestMethod]
        public void PostTipoDeCanal()
        {
            TipoDeCanalesController TipoDeCanal = new TipoDeCanalesController();
            Assert.Equals(TipoDeCanal.PostTipoDeCanal(new Models.TipoDeCanal { Descripcion = "Unit Test Description", Nombre = "Test" }).StatusCode,
                System.Net.HttpStatusCode.Created);
        }
    }

1 个答案:

答案 0 :(得分:3)

如果你不需要Request中的任何内容,你可以满足这样的实例:

TipoDeCanalesController TipoDeCanal = new TipoDeCanalesController();

TipoDeCanal.Request = new HttpRequestMessage();
TipoDeCanal.Request.SetConfiguration(new HttpConfiguration());

Assert.Equals(TipoDeCanal.PostTipoDeCanal(new Models.TipoDeCanal { Descripcion = "Unit Test Description", Nombre = "Test" }).StatusCode,
                System.Net.HttpStatusCode.Created);