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