Unit testing JSON ModelBinding in Nancy -


i trying test json model binding in nancyfx.

the request works when tested in browser, cannot unit test pass. when debug test, find model returned null

 var model = this.bind<eventrequestmodel>(); 

is null;

here simplified example of i'm doing:

nancymodule:

    post["/events"] = _ =>     {         // convert request model , validate         try         {             var model = this.bind<eventrequestmodel>();             var result = this.validate(model);             if (!result.isvalid)                 throw  new exception("model not valid");              return httpstatuscode.ok          }          catch (exception ex)          {              _logger.logerror(ex);              return httpstatuscode.badrequest;          }                          }; 

unit test:

    [fact]     public void returnokongoodrequest()     {         // create valid model         var model = new eventrequestmodel()             {                 toprightlat = 100,                 toprightlong = 100,                 bottomleftlat = 100,                 bottomleftlong = 100             };          var response = _browser.post("/api/events", =>             {                 with.jsonbody(model);             });          assert.equal(httpstatuscode.ok, response.statuscode);      } 

i have tried writing json directly body , doing this:

    var json = "{'toprightlat' : 0, 'toprightlong': 0, 'bottomleftlat':  0, 'bottomleftlong': 0}"     var response = _browser.post("/api/events", =>         {             with.header("content-type", "application/json");             with.body(json);          }); 

this json body works when test endpoint manually not in unit test. doing wrong?

the reason failed because had not added model binding dependencies configurablebootstrapper when setting test.

this (in test set up) fixed it

_bootstrapper = new configurablebootstrapper(with => {     ...     with.dependency<ifluentadapterfactory>(_fluentvalidationfatory);     with.dependency<imodelvalidatorfactory>(_modelvalidatorfactory);     ... } 

Comments