Reputation: 8208
I have these two tests:
[TestFixture(Category = "MyCategory")]
public class MyTestFixture
{
private int count = 0;
[SetUp]
public void BeforeEachTest()
{
this.count++;
}
[Test]
public void AssertCountIs1_A()
{
Assert.AreEqual(1, this.count);
}
[Test]
public void AssertCountIs1_B()
{
Assert.AreEqual(1, this.count);
}
}
One of the two tests will always fail because count will be 1 for one of the tests, but 2 for the other test. I know that this is because the count
member exists for the life of the MyTestFixture
instance.
Can I declare that I want count
to only exist for the life of the given test? For instance, is there some attribute I can prepend to count
so that both of these tests succeed?
If not, I can put together a workaround that keeps a dictionary that maps test names to counts. I'd rather avoid that if I can though.
Upvotes: 0
Views: 1233
Reputation: 8208
In the example code, if NUnit was configured to create a new instance of the class per-test, the assertions would succeed. (MSTest and XUnit already do this). This is not available in NUnit, so that example code would need to be updated so that the assertions succeed. Here's the discussion https://github.com/nunit/nunit/issues/2574
Upvotes: 0
Reputation: 13736
Yes, NUnit has such variables, or at least C# has them. They are called local variables and are declared within the body of your test. As such, they only exist during the time that the test is running and are re-initialized each time.
Whether you can use them for your purpose depends on what your purpose is. Your question doesn't give much info about this. I assume that is because you have tried to "boil down" the problem to something simple, which we can all understand. Unfortunately, if you over-simplify it becomes difficult to help you.
Based on the extended discussion in comments, it appears you may not want local variables because you want them to live across multiple executions of the test. Is that correct? A more complete question may get you a more complete answer.
Upvotes: 0