Question

My Unit Test:

[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....
}

The first time I run the test (VS2013 using Resharper as TestRunner) I see that response.Body is my expected JSON string:

[{"location":"Somewhere","location_Name":"Somewhere Name"}]

but later after I've worked a bit and re-run, all tests fail and the response.Body is now:

Location,Location_Name
Somewhere,Somewhere Name

instead of being JSON. Why/How do I force Json?

The Module looks like this:

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 looks like this (and has a load of added utility methods but doesn't override anything) :

public abstract class ModuleBase : NancyModule
{
    protected ModuleBase()
    {
    }

    protected ModuleBase(string modulePath)
        : base(modulePath)
    {
    }

    //other protected methods but nothing overridden
}
Was it helpful?

Solution

I still don't know why it switches, but Nancy does allow setting the client Accept header to force 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");
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top