Ohad
Ohad

Reputation: 353

Run each theory in different test class

Assume I have a test class with a theory method that runs with two inputs, "irrelevant" and "irrelevant2". The test first checks if a static class "IsInitialized", if it does, the test fails.

Then, the test initializes the static class by calling "Initialize".

[Theory]
[InlineData("irrelevant")]
[InlineData("irrelevant2")]
public void Test(string param)
{
    if (MyStaticClass.IsInitialized()) { throw new Exception(); }
    MyStaticClass.Initialize();
}

public static class MyStaticClass
{
    private static bool Initialized = false;

    public static void Initialize()
    {
        Initialized = true;
    }

    public static bool IsInitialized()
    {
        return Initialized;
    }
}

What I expect is that both tests will pass, as the static class is only initialized after calling "Initialize". However, the result is that the first test pass and the second fails, because the static class remains in memory. I'd expect the static class state to revert to its initial. I can understand why this is happening, because of using a static. However, I'm trying to figure out if there's a way to configure the test to dispose the memory of the static class as if I would run a new test case.

This would also happen if I had two "Fact"s with the same code in them. When running each fact separately, both tests would pass. When running the test class, one would pass (the first) and the second would fail.

Upvotes: 0

Views: 506

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29302

What you're describing is expected behavior. If you set the value of static field Initialized to "true" in one test, when you run the next test it's going to be "true".

There are a few ways to look at this:

  • If all you're testing is that setting a field's value actually works, just don't test that. It's not so much a behavior of your code as a feature of the language. Do we need to write tests to verify that setting a property really sets it? Likely not.
  • If you have to test it, don't write tests that must fail if the language works correctly. Write a test that verifies that the value is whatever you set it to. A test that verifies what the value is not isn't very useful.
  • Consider not using a static class and property. The reasons for using a static vs. an instance class are specific to whatever you're coding. I don't know your reasons. But often the challenges we encounter when testing reflect the problems we'll have when using the code "for real."
  • You asked if you could "dispose" it from memory. You can't do that, or at least the process for doing it is so complicated that you shouldn't do it. You could add a method to your static class that "resets" the value. But that's a little messy. If we have to add methods to static classes just so we can test them then maybe we should consider not using a static class.

Upvotes: 1

Related Questions