Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflicts between 2 unit tests c# using a static class

I have conflicts between some of my unit tests. I have a class with a static event, when I run each test one at a time I have no problem, but when I run all tests in a batch, the tests which are firing the event will crash because of the registred listeners (which have registred to the event in the previous tests).

Obviously I don't want the event handlers to be executed when the tested class fires the event, so what is the best solution ?

I know I wouldn't have the problem if the event was not static, but I would prefer not have to redesign this if there is another solution.

Detaching all the event listeners before running the test could be a solution, but I think it is impossible to do it from outside of the class (which seems normal cause we don't want a client being able to detach all other listeners), and doing it from the inside would means that I have to add a method in the class for the only purpose of the unit tests, which is as bad practice.

Is there a way to run the test in an isolation mode that would prevent other previous tests to impact it ? Like if it was run in a completely separated process so that I don't get the same reference to the static event ? (But I still need to be able to executes all tests in batch with a simple click)

Thanks for your help and ideas !

For information I am using Visual Studio 2012 unit test framework.

like image 447
Jonathan Avatar asked Jul 23 '26 20:07

Jonathan


1 Answers

Somewhere within each individual test you are going to attach yourself to the static event. So simply before the assert simply detach yourself or better guard the detaching within a finally block:

[TestCase]
public void MyTestDetachingBeforeAssert()
{
    bool finishedCalled = false;
    var eventListener = new EventHandler((sender, e) => finishedCalled = true);

        MyClass.Finished += eventListener;
        // Can lead to detach problems if this throws an exception!
        MyClass.DoSomething();
        MyClass.Finished -= eventListener;

        Assert.That(finishedCalled);
}

[TestCase]
public void MyTestDetachingInFinally()
{
    bool finishedCalled = false;
    var eventListener = new EventHandler((sender, e) => finishedCalled = true);

    try
    {
        MyClass.Finished += eventListener;
        MyClass.DoSomething();

        Assert.That(finishedCalled);
    }
    finally
    {
        MyClass.Finished -= eventListener;
    }
}
like image 76
Oliver Avatar answered Jul 25 '26 11:07

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!