Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 start with the test?

like image 811
Marcus Hammarberg Avatar asked Sep 09 '11 17:09

Marcus Hammarberg


1 Answers

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

like image 68
Steven Robbins Avatar answered Nov 16 '22 01:11

Steven Robbins