【发布时间】:2014-09-04 17:32:07
【问题描述】:
我正在尝试测试从我的 Nancy 应用程序返回的模型是否符合预期。我遵循了文档here,但每当我调用GetModel<T> 扩展方法时,它都会抛出KeyNotFoundException。
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
我知道错误的含义,但我不明白为什么会抛出它。
这是我的模块
public class SanityModule : NancyModule
{
public SanityModule()
{
Get["sanity-check"] = _ => Negotiate.WithModel(new SanityViewModel { Id = 1 })
.WithStatusCode(HttpStatusCode.OK);
}
}
我的视图模型
public class SanityViewModel
{
public int Id { get; set; }
}
这是我的测试
[TestFixture]
public class SanityModuleTests
{
[Test]
public void Sanity_Check()
{
// Arrange
var browser = new Browser(with =>
{
with.Module<SanityModule>();
with.ViewFactory<TestingViewFactory>();
});
// Act
var result = browser.Get("/sanity-check", with =>
{
with.HttpRequest();
with.Header("accept", "application/json");
});
var model = result.GetModel<SanityViewModel>();
// Asset
model.Id.ShouldBeEquivalentTo(1);
}
}
调试这个测试表明该模块被命中并且完成得很好。运行应用程序显示响应符合预期。
有人能解释一下吗?
【问题讨论】:
-
我相信
GetModel<T>的目的是让模型位于渲染的 html 视图后面。您可以将 json 反序列化到 SanityModel 进行检查。
标签: nancy