caloggins
7/30/2014 - 7:32 PM

TestinNancyWithMSOwinTesting.cs

namespace TestinNancyWithOwinTesting
{
    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Nancy;
    using Nancy.Bootstrapper;
    using Nancy.Testing;
    using Owin;
    using Microsoft.Owin.Testing;
    using Xunit;

    public class Class1
    {
        [Fact]
        public void NancyTest()
        {
            // Arrange
            var browser = new Browser(with => with.Module<ConfigBootTestModule>());

            // Act
            BrowserResponse response = browser.Get("/config");

            // Assert
            Assert.Equal("Hello configured fellow", response.Body.AsString());
        }

        [Fact]
        public async Task OwinTest()
        {
            // Arrange
            var httpClient = CreateHttpClient(with => with.Module<ConfigBootTestModule>());

            // Act
            var response = await httpClient.GetAsync("http://localhost/config");
            var body = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal("Hello configured fellow", body);
        }

        private static HttpClient CreateHttpClient(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> configureBootstrapperAction)
        {
            return TestServer.Create(builder => 
                new Startup(new ConfigurableBootstrapper(configureBootstrapperAction)).Configuration(builder))
                .CreateHttpClient();
        }

        private class Startup
        {
            private readonly INancyBootstrapper _nancyBootstrapper;

            public Startup(INancyBootstrapper nancyBootstrapper)
            {
                _nancyBootstrapper = nancyBootstrapper;
            }

            public void Configuration(IAppBuilder builder)
            {
                builder.UseNancy(_nancyBootstrapper);
            }
        }
    }

    public class ConfigBootTestModule : NancyModule
    {
        public ConfigBootTestModule() : base("/config")
        {
            Get["/"] = p => "Hello configured fellow";
        }
    }
}