In testing singleton classes we need the single instance to "go away" after each test. Is there a way to configure nunit to recreate the test app domain after each test, or at least after each fixture?
-
If the singleton's setup is so complex that it needs to be tested every time you call it, can you bottle up the creation logic into a method and then test that method instead? – roufamatic Feb 25 '10 at 17:59
3 Answers
You could provide the means to renew the singleton instance when testing via a conditional method.
// CUT
public sealed class Singleton{
private static Singleton _instance = new Singleton();
private Singleton()
{
// construct.
}
public static Singleton Instance{
get{
return _instance;
}
}
[Conditional ("DEBUG")]
public static void FreshInstance (){
_instance = new Singleton();
}
}
// NUnit
[TestFixture]
public class SingletonTests{
[SetUp]
public void SetUp(){
Singleton.FreshInstance();
}
}

- 3,881
- 5
- 33
- 59
I needed to do the the exact same thing, so I created a library which basically takes the current test and re-executes it in a new AppDomain. It's a nuget package called NUnit.ApplicationDomain and is open source.
Example Code:
[Test, RunInApplicationDomain]
public void Method()
{
Console.WriteLine("I'm in a different AppDomain")
}

- 8,017
- 3
- 43
- 63
I guess I'm missing something here Ralph. Just for my own benefit, can you explain why adding methods with the following attributes to your Test Class that drop and recreate your instances wouldn't work for you?
Adding these attributes for methods should make them run before / after each test.
[SetUp]
[TearDown]
Adding these attributes for methods should make them run before / after the fixture.
[TestFixtureSetUp]
[TestFixtureTearDown]
Is there a reason why using methods with these attributes couldn't create and destroy your domain between tests?

- 16,892
- 20
- 80
- 117

- 1,880
- 1
- 14
- 20