Search code examples
unit-testingnancy

NancyFX: Can I force my unit-test browser to be authenticated by default?


Here is a unit test that shows me authenticating my Nancy browser (other code has been snipped out). I was wondering if there was a smarter, DRYer way to do this?

[Fact]
public void Login__Should_redirect_from_login_to_requested_page_if_credentials_are_correct()
{
    var browser = Fake.Browser();
    var response = browser.Post("/login", with =>
                                         {
                                           with.HttpRequest();
                                           with.FormValue("UserName", userName);
                                           with.FormValue("Password", password);
                                          });
    response.ShouldHaveRedirectedTo("/");
}

Solution

  • It looks like you have a method that delivers back a Browser instance:Fake.Browser() so why not just rewrite this to provide an authenticated version if required. Something like this perhaps:

    public static Browser Browser(string username = null, string password = null)
    {
        var browser = new Browser(new UnitTestBootstrapper());
        if (username.IsEmpty() || password.IsEmpty()) return browser;
        return browser.Post("/login", with =>
                                            {
                                                with.HttpRequest();
                                                with.FormValue("Username", username);
                                                with.FormValue("Password", password);
                                            }).Then;
    }