3

我正在尝试在 NancyFx 中测试 JSON 模型绑定。

该请求在浏览器中测试时有效,但我无法通过单元测试。当我调试测试时,我发现返回的模型是空的

 var model = this.Bind<EventRequestModel>();

始终为空;

这是我正在做的一个简化示例:

南希模块:

    Post["/Events"] = _ =>
    {
        // Convert request to model and validate
        try
        {
            var model = this.Bind<EventRequestModel>();
            var result = this.Validate(model);
            if (!result.IsValid)
                throw  new Exception("Model was not valid");

            return HttpStatusCode.OK
         }
         catch (Exception ex)
         {
             _logger.LogError(ex);
             return HttpStatusCode.BadRequest;
         }                    
     };

单元测试:

    [Fact]
    public void ReturnOkOnGoodRequest()
    {
        // Create a valid model
        var model = new EventRequestModel()
            {
                TopRightLat = 100,
                TopRightLong = 100,
                BottomLeftLat = 100,
                BottomLeftLong = 100
            };

        var response = _browser.Post("/API/Events", with =>
            {
                with.JsonBody(model);
            });

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
     }

我还尝试将 JSON 直接写入正文并执行以下操作:

    var json = "{'TopRightLat' : 0, 'TopRightLong': 0, 'BottomLeftLat':  0, 'BottomLeftLong': 0}"
    var response = _browser.Post("/API/Events", with =>
        {
            with.Header("Content-Type", "application/json");
            with.Body(json);
         });

这个 JSON 正文在我手动测试端点时有效,但在我的单元测试中无效。我究竟做错了什么?

4

1 回答 1

4

失败的原因是我ConfigurableBootstrapper在设置测试时没有添加模型绑定依赖项。

这(在测试设置中)修复了它

_bootstrapper = new ConfigurableBootstrapper(with =>
{
    ...
    with.Dependency<IFluentAdapterFactory>(_fluentValidationFatory);
    with.Dependency<IModelValidatorFactory>(_modelValidatorFactory);
    ...
}
于 2013-07-19T15:19:12.403 回答