Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("/");
}
like image 426
biofractal Avatar asked Dec 30 '25 18:12

biofractal


1 Answers

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;
}
like image 153
code mariner Avatar answered Jan 02 '26 17:01

code mariner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!