Last active
August 29, 2015 14:21
-
-
Save rikkit/361b15bd51e0600f2aa2 to your computer and use it in GitHub Desktop.
Self host Nancy for an integration test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Nancy; | |
using Nancy.Extensions; | |
using Nancy.Responses; | |
using Nancy.Hosting.Self; | |
using Nancy.TinyIoc; | |
using Nancy.Bootstrapper; | |
using System; | |
using System.Collections.Generic; | |
using System.Reflection; | |
using System.Runtime.CompilerServices; | |
public class TestConfiguration | |
{ | |
public Dictionary<string, Func<dynamic, IResponseFormatter, dynamic>> GetRoutes { get; set; } | |
} | |
public class TestModule : NancyModule { | |
public TestModule(TestConfiguration config) { | |
foreach (var route in config.GetRoutes) | |
{ | |
var get = route; | |
Get[route.Key] = p => get.Value(p, Response); | |
} | |
} | |
} | |
public class TestBootstrapper : DefaultNancyBootstrapper | |
{ | |
private readonly TestConfiguration _config; | |
public TestBootstrapper(TestConfiguration config) | |
{ | |
_config = config; | |
} | |
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) | |
{ | |
container.Register<TestConfiguration>(_config); | |
} | |
/// <summary> | |
/// Register only NancyModules found in this assembly | |
/// </summary> | |
protected override void ConfigureApplicationContainer(TinyIoCContainer container) | |
{ | |
container.AutoRegister(new[]{Assembly.GetAssembly(typeof(TestModule))}); | |
} | |
} | |
public class NancyHostContainer { | |
private NancyHost _host; | |
public NancyHostContainer(Uri testUri, TestConfiguration config) | |
{ | |
var bootStrapper = new TestBootstrapper(config); | |
var hostConfig = new HostConfiguration | |
{ | |
UrlReservations = new UrlReservations {CreateAutomatically = true} | |
}; | |
_host = new NancyHost(bootStrapper, hostConfig, testUri); | |
} | |
public void Start(){ | |
_host.Start(); | |
} | |
public void Stop() { | |
_host.Stop(); | |
} | |
} | |
[TestClass] | |
public class Tests { | |
[TestMethod] | |
public void Test1 { | |
var testUri = new Uri("http://localhost:6060"); | |
// has to be an object, Nancy uses dependency injection internally to get this into the module | |
var config = new TestConfiguration | |
{ | |
GetRoutes = new Dictionary<string, Func<dynamic, IResponseFormatter, dynamic>> | |
{ | |
{"/", (parameters, formatter) => formatter.AsJson("{}")} | |
} | |
}; | |
var nancy = new NancyHostContainer(testUri, config) | |
nancy.Start(); | |
// ... test | |
nancy.Stop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment