I'm using Nunit and I wonder if there is a way to return to the real initialization state including all the singletons that constructed already.
currently I've solved it with a workaround of adding to the singletons a reset method and I don't like it because now my production code is not clean.
as far as I understand the single tones will be initialized once and be kept in the heap which is available during all the tests executions.
Is there a way to clean the heap at the teardown function of the Nunit testfixture?
I've managed to reproduce the issue with the following (ugly) code sample, you can see that when both tests executed one after the other the second one failed...
[TestFixture]
public class SingletonCleanups
{
private MySingleTonsHolder _holder;
[SetUp]
public void Setup()
{
_holder = new MySingleTonsHolder();
}
[Test]
public void DoWork_FirstExecution_SingleCalledOnce()
{
_holder.DoWork();
Assert.AreEqual(1, MySingleTonsHolder.MySingleTon.CalledCount);
}
[Test]
public void DoWork_SecondExecution_SingleCalledOnce()
{
_holder.DoWork();
Assert.AreEqual(1, MySingleTonsHolder.MySingleTon.CalledCount);
}
}
public class MySingleTonsHolder
{
public static MySingleTon MySingleTon => MySingleTon.Instance();
public void DoWork()
{
MySingleTon.Instance().CalledCount++;
}
}
public class MySingleTon
{
private static MySingleTon _instance;
public static MySingleTon Instance()
{
if (_instance==null)
{
_instance = new MySingleTon();
}
return _instance;
}
public int CalledCount { get; set; }
private MySingleTon()
{
CalledCount = 0;
}
}