我们假设我有这个南希模块
public class ProductModule : NancyModule
{
public ProductModule(IProductRepository repo)
{
Get["/products/list"] = _ =>
{
ViewBag.Categories = repo.GetAllCategories();
return repo.GetAllProducts();
};
}
}
我使用Razor作为ViewEngine,我可以显示产品列表。
现在我希望能够在Windows窗体应用程序中执行相同的请求。我知道我可以做点什么
var bootstrapper = new CustomBootstrapper();
bootstrapper.Initialise();
var engine = bootstrapper.GetEngine();
var request = new Request("GET", "/products/list.xml", "http");
var context = engine.HandleRequest(request);
无论如何,这不符合我的需求,因为它涉及整个http管道并序列化我的IQueryable
。但是在我的Windows窗体应用程序中,我已经为IQueryable<>
个对象提供了正确的页面支持。目前我应该有一些带有
public class ProductController
{
dynamic ViewBag = new ExpandoObject();
public dynamic List()
{
ViewBag.Categories = repo.GetAllCategories();
return repo.GetAllProducts();
}
}
我想摆脱它,只使用我的南希模块。
基本上这必须以某种方式实现,因为在我的剃刀视图中,我完全拥有我想要的东西,并且可以完全访问ViewBag和Model。
我已经下载了源代码但尚未设法找到正确的按钮。
任何建议都将不胜感激。
答案 0 :(得分:0)
虽然我不确定为什么@ eth0的建议在你的具体情况下不合适,但Nancy.Testing
至少提供了绕过网络堆栈的方法。
var bootstrapper = new CustomBootstrapper();
var browser = new Browser(bootstrapper);
var result = browser.Get("/products/list.xml", with => { with.HttpRequest(); });
有关详细信息,请参阅官方文档:Testing your application
答案 1 :(得分:0)
深入挖掘测试扩展
public class GetModelExtententionsTests
{
private readonly Browser _browser;
public GetModelExtententionsTests()
{
this._browser = new Browser(with => {
with.Module<AModuleToTestExtensionMethodsWith>();
with.ViewFactory<TestingViewFactory>();
});
}
[Fact]
public void Can_get_the_model_and_read_the_values()
{
var response = this._browser.Get("/testingViewFactory");
var model = response.GetModel<ViewFactoryTestModel>();
Assert.Equal("A value", model.AString);
}
}
注意:使用这些扩展方法需要使用 TestingViewFactory,在测试Browser对象上设置。这是一个包装 ViewFactory保存模型然后用它公开它 扩展方法。不过,你不必过于考虑, 只确保设置TestingViewFactory(例如 with.ViewFactory();)
所以基本上解决方案是实现一个在渲染视图之前存储模型的viewfactory。