我的单元测试:
[Fact]
public void TimeOnSite_3_Returns_an_Array_of_location_and_location_name()
{
//A
var response = new Browser(new Bootstrapper()).Get("/reports/data/timeonsite",
with =>
{
with.HttpRequest();
with.Query("type", "3");
});
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//A
var raw = response.Body.AsString();
Console.WriteLine("TimeOnSite3:{0}", raw);
///...etc....
}
我第一次运行测试(VS2013使用Resharper作为TestRunner)我看到response.Body是我期望的JSON字符串:
[{"location":"Somewhere","location_Name":"Somewhere Name"}]
但是稍后我做了一些工作并重新运行后,所有测试都失败了,而且响应。现在是:
Location,Location_Name
Somewhere,Somewhere Name
而不是JSON。为什么/如何强迫Json?
模块看起来像这样:
public class ReportDataModule : ModuleBase
{
static readonly Lazy<DataSource> DbProviderDataLoader = new Lazy<DataSource>(() => new DataSource());
private readonly Lazy<DataSource> _dataLoader;
public ReportDataModule() : this("/reports/data", DbProviderDataLoader){}
public ReportDataModule(string path, Lazy<DataSource> reportDataLoader) : base(path)
{
//
// _dataLoader.Value.TimeOnJob<TimeOnJobSummary> returns an IEnumerable<TimeOnJobSummary> (underneath it's a List<>)
// TimeOnJobSummary is
// public class TimeOnSiteSummary
// {
// public DateTime Date_Group { get; set; }
// public int Qty { get; set; }
// public int Avg_Days { get; set; }
// }
Get["/timeOnSite"] =
ctx =>
Negotiate.WithModel(_dataLoader.Value.TimeOnJob<TimeOnJobSummary>((int) (Request.Query.type),(string)Request.Query.dateGroup));
_dataLoader = reportDataLoader;
}
}
ModuleBase
看起来像这样(并且有一些添加的实用程序方法,但不会覆盖任何内容):
public abstract class ModuleBase : NancyModule
{
protected ModuleBase()
{
}
protected ModuleBase(string modulePath)
: base(modulePath)
{
}
//other protected methods but nothing overridden
}
答案 0 :(得分:2)
我仍然不知道为什么会切换,但Nancy确实允许设置客户端Accept标头来强制json:
var response = new Browser(new Bootstrapper()).Get("/reports/data/timeonsite",
with =>
{
with.HttpRequest();
with.Header("Accept","application/json"); // <-- add an Accept header
with.Query("type", "3");
});