Wednesday 4 December 2013

NancyFx - Testing modules requiring authentication

I've recently been using NancyFx to build a pretty simple API. It's a great little framework, lightweight and super extensible. It's also been designed with testing in mind.

I developed a good chunk of the API without implementing any authentication mechanism. Later on I protected certain Nancy Modules by using Nancy's RequiresAuthentication() method which caused the unit tests around the controllers to begin failing. What I needed was to tell Nancy there was an authenticated user present.

Using Nancy's Browser() with the configurable bootstrapper, I loaded the module I needed to test:


But how to tell Nancy there is an authenticated user? Well all Nancy does is check if an instance of IUserIdentity with a UserName is present on the Context (authentication plugins set this!). We can get access to the context at the beginning of the request using the configurable bootstrapper, so modifying our Browser set up to the following is all we need to do, ta da, Nancy believes a user has been authenticated.


No comments:

Post a Comment