Reputation: 353
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
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:
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."Upvotes: 1