代码之家  ›  专栏  ›  技术社区  ›  Jürgen Steinblock

我可以自己调用南希模块吗

  •  2
  • Jürgen Steinblock  · 技术社区  · 12 年前

    假设我有这个Nancy模块

    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。

    我已经下载了源代码,但还没有找到合适的按钮。

    如有任何建议,将不胜感激。

    2 回复  |  直到 12 年前
        1
  •  0
  •   CodeFox    11 年前

    虽然我不确定为什么@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

        2
  •  0
  •   Mogsdad    11 年前

    我想我在 nancy testing framework

    使用测试扩展深入挖掘

    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,设置在测试浏览器对象上。这是一个包装 保存模型,然后使用 扩展方法。不过你不必想太多, 仅确保设置TestingViewFactory(例如。 with.ViewFactory();)。

    因此,基本上解决方案是实现一个视图工厂,在渲染视图之前存储模型。

    推荐文章