Test driving Nancy Modules

血红的双手。 提交于 2019-12-10 01:52:15

问题


Ok - I love NancyFx. Writing a web application with that few lines is just amazing!

But how do you test drive your NancyModules on the unit level?

Please note that I am aware of the excellent testframework supplied with Nancy (Nancy.Testing on NuGet), which gives excellent ways to test the whole (almost) application stack. But now I mean the unit level test I use to flesh out the contents of my NancyModule, in TDD fashion.

Since the routes are defined in the constructor, often together with a lamda expression that constitute the whole action, it feels a bit "unreachable" from a unit test. But have I missed something obvious on how to test the actions of the route?

For example, how would a unit test for this simple application look?

public class ResouceModule : NancyModule 
{
   private IProductRepository _productRepo;

   public ResourceModule(IProductRepository repo) : base("/products") 
   {
        Get["/list"] = parameters => { 
           return View["productList.cshtml", repo.GetAllProducts()];
        };
   }
}

See there - now I wrote the production code before the test... :) Any suggestions on how to start with the test?


回答1:


You can do test first dev with the testing tools we provide:

  • In your test startup configure a bootstrapper that only contains the module you have under test and any any fake objects you want.
  • In your test execute a specific route (like GET /list) - you might want a small helper for this to remove some repeated code perhaps.
  • Assert on what comes back - you have full access to the request and response objects (for headers, cookies etc), along with helpers for HTML bodies and, coming in 1.8, helpers for handing JSON, XML and just string responses in the body.
  • Move onto the next route, rinse and repeat.

Ok, so you're not just testing the module, but if you look at the call stack, there's not much going on before or after you hit your route so it's not that big of a deal in my book :-) If you really do want to test the module in complete isolation then you can just construct it yourself and poke the individual routes accordingly (they're just dictionaries in the module).




回答2:


As part of Nancy.Testing you can use the configurable bootsrapper to control the setup, including the IoC setup. That should enable testing the module without lower level dependencies, and enable TDD.



来源:https://stackoverflow.com/questions/7365306/test-driving-nancy-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!