我们使用NancyFx来托管单个页面应用程序和多个ReST端点。代码和测试使用相同的引导程序,唯一的区别是在测试中我们使用测试框架中的Nancy Browser。NancyFx测试返回无效的Json
如果我从网站返回一个简单的对象,那么所有的功能都可以像预期的那样通过应用程序或测试框架进行。然而,真正的问题是我们要返回的对象包含一些动态数据,尽管它本身不是一个动态对象。该应用程序工作正常,但测试失败,因为JSON无效,字符串缺少引号和日期格式不正确。
var browser = new Browser(bootstrapper);
_response = browser.Get("http://localhost/...", with =>
{
with.HttpRequest();
with.Header("Accept", "application/json");
});
var bstr = _response.Body.AsString();
我已经附着在管道AfterRequest方法的方法,同时测试,我可以看到JSON字符串看起来不错,通过观察在NancyContext响应特性,但只要我们得到的响应对象返回从浏览器并将其转换为字符串,它不再有效的JSON。
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
pipelines.AfterRequest += Foo;
}
private void Foo(NancyContext obj)
{
//Can see the Response on the NancyContext here
}
如果我不能解决这个问题,我会考虑放弃南希测试框架,只是在测试环境中自我托管。
编辑
我得到使用NancySelfHost类似的结果。它看起来像是在使用自主或测试浏览器时没有采用Json.Net序列化程序。我正在使用在Tiny IoC https://github.com/NancyFx/Nancy.Serialization.JsonNet中注册自定义串行器的标准设置。
public class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
this.ContractResolver = new CamelCasePropertyNamesContractResolver();
this.Formatting = Formatting.Indented;
}
}
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register(typeof(JsonSerializer), typeof(CustomJsonSerializer));
}
}
我没有提到它的问题的第一部分,但在编辑我提到这是用在自拍主机或当我们在做什么,但是Json.Net串行没有被拾起南希测试浏览器。只有在通过Asp.Net托管时。我确实有一个工作,我将作为答案发布。 – Bronumski 2014-10-07 12:51:02
奇怪 - 我在自己的主机上检查了它,并且它与来自nuget的Json.NET序列化程序工作正常。 – 2014-10-07 16:05:07