gpt4 book ai didi

json - 在 Nancy 中对 JSON ModelBinding 进行单元测试

转载 作者:行者123 更新时间:2023-12-04 02:50:59 25 4
gpt4 key购买 nike

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

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

 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 正文在我手动测试端点时有效,但在我的单元测试中无效。我做错了什么?

最佳答案

失败的原因是因为我在设置测试时没有将模型绑定(bind)依赖项添加到 ConfigurableBootstrapper

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

_bootstrapper = new ConfigurableBootstrapper(with =>
{
...
with.Dependency<IFluentAdapterFactory>(_fluentValidationFatory);
with.Dependency<IModelValidatorFactory>(_modelValidatorFactory);
...
}

关于json - 在 Nancy 中对 JSON ModelBinding 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17742210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com