2013-07-19 59 views
2

我想在NancyFx中測試JSON模型綁定。單元測試在南希的JSON ModelBinding

該請求在瀏覽器中測試時有效,但我無法通過單元測試。當我調試測試,我發現返回的模式爲null從

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

總是空;

下面是我在做什麼一個簡單的例子:

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; 
     }      
    }; 

單元測試:

[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

這個失敗的原因是因爲我在設置測試時沒有將模型綁定依賴項添加到ConfigurableBootstrapper

這(在測試設置)固定它

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