Skip to content

Instantly share code, notes, and snippets.

@scottmcarthur
Created September 25, 2014 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmcarthur/f7934dccf3d5ba2fd6fc to your computer and use it in GitHub Desktop.
Save scottmcarthur/f7934dccf3d5ba2fd6fc to your computer and use it in GitHub Desktop.
ServiceStack AppHost Running in it's own AppDomain for Tests
using System;
using ServiceStack;
using System.Runtime.Remoting;
using NUnit.Framework;
namespace MyApp.Tests
{
public class AppHost : AppSelfHostBase
{
public AppHost(): base("My ServiceStack Service", typeof(AppHost).Assembly)
{
}
public override void Configure(Funq.Container container)
{
container.Register<MyTest>(c => new MyTest());
}
}
public class MyTest
{
public string Name { get { return "Hello"; } }
}
public class IsolatedAppHost : MarshalByRefObject
{
readonly AppHost Host;
public IsolatedAppHost()
{
// Start your HttpTestableAppHost here
Host = new AppHost();
Host.Init();
Host.Start("http://*:8090/");
Console.WriteLine("ServiceStack is running in AppDomain '{0}'", AppDomain.CurrentDomain.FriendlyName);
}
public void RunTest(Action<AppHost> test)
{
test.Invoke(Host);
}
public void Teardown()
{
if(Host != null)
{
Console.WriteLine("Shutting down ServiceStack host");
if(Host.HasStarted)
Host.Stop();
Host.Dispose();
}
}
}
[TestFixture]
public class Test
{
AppDomain ServiceStackAppDomain;
IsolatedAppHost IsolatedAppHost;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
// Get the assembly of our host
var assemblyName = typeof(IsolatedAppHost).Assembly.GetName();
ServiceStackAppDomain = AppDomain.CreateDomain("ServiceStackAppDomain");
ServiceStackAppDomain.Load(assemblyName);
var handle = ServiceStackAppDomain.CreateInstance(assemblyName.FullName, "MyApp.Tests.IsolatedAppHost");
IsolatedAppHost = (IsolatedAppHost)handle.Unwrap();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
// Tell ServiceStack to stop the host
IsolatedAppHost.Teardown();
// Shutdown the ServiceStack application
AppDomain.Unload(ServiceStackAppDomain);
ServiceStackAppDomain = null;
}
[Test]
public void TestWillPass()
{
IsolatedAppHost.RunTest(appHost => {
var t = appHost.TryResolve<MyTest>();
Assert.That(t.Name, Is.EqualTo("Hello"));
});
}
[Test]
public void TestWillFail()
{
IsolatedAppHost.RunTest(appHost => {
var t = appHost.TryResolve<MyTest>();
Assert.That(t.Name, Is.EqualTo("World"));
});
}
}
}
@squidge
Copy link

squidge commented Feb 2, 2015

Hi, Is this the only approach to run an integration test to a servicestack endpoint without getting the instance exception?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment