开发者

Test driving Nancy Modules

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 s开发者_开发问答tart with the test?


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜