Reputation: 1423
I am trying to test JSON model binding in NancyFx.
The request works when tested in the browser, but I cannot get the unit test to pass. When I debug the test, I find that the model returned is null from
var model = this.Bind<EventRequestModel>();
is always null;
Here is a simplified example of what i'm doing:
NancyModule:
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;
}
};
Unit Test:
[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);
}
I have also tried writing JSON directly into the body and doing something like this:
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);
});
This JSON body works when I test the endpoint manually but not in my unit test. What am I doing wrong?
Upvotes: 3
Views: 2052
Reputation: 1423
The reason this failed was because I had not added the model binding dependencies to the ConfigurableBootstrapper
when setting up the test.
This (in the test set up) fixed it
_bootstrapper = new ConfigurableBootstrapper(with =>
{
...
with.Dependency<IFluentAdapterFactory>(_fluentValidationFatory);
with.Dependency<IModelValidatorFactory>(_modelValidatorFactory);
...
}
Upvotes: 4