user8075070
user8075070

Reputation:

NUnit - Unit Test - Dispose issue

namespace Game.SoccerGame

 [TestFixture]
    public class Score_is_0_0 : SoccerGame
    {
        [SetUp]
        public void SetUp()
        {
            GivenTheScoreIs(0,0);
        }

  [TearDown]
        public void CleanUp()
        {
           

        }

        [Test]
        public void When_Team1_Scores()
        {
            WhenTeam1Scores();

            Assert.That(ScoreOutput, Is.EqualTo("1:0"));
        }

        [Test]
        public void When_Team2_Scores()
        {
            WhenTeam2Scores();

            Assert.That(ScoreOutput, Is.EqualTo("0:1"));
        }
    }

Expected:
When_Team1_Scores() = 1:0
When_Team1_Scores() = 0:1

When I run the tests individually they work as expected. The issue I am having is when I run the tests in the class all at the same time. When I do this the results are:

When_Team1_Scores() = 1:0
When_Team1_Scores() = 1:1

the ScoreOutput keeps its state after the first test and thus my second test fails

What is the best approach the kill the state in-between tests in the TearDown?

I have the object below in a separate class SoccerGame that I inherit that controls the score state


public abstract class SoccerGame : IDisposable
private SetScore currentScore = new SetScore();

 protected string ScoreOutput => currentScore.ToString();

 public void Dispose()
        {
          
        }

I tried to use IDisposable but it doesn't see to work or I am implementing it wrong?

Upvotes: 1

Views: 2270

Answers (1)

Charlie
Charlie

Reputation: 13681

When using NUnit, a single instance of the fixture is created and used for all the tests in the fixture. Because of that, any state that needs to be initialized should be taken care of in the SetUp method, which runs before each test.

You don't show the code for your method GivenTheScoreIs but it sounds like it's supposed to initialize the score. To ensure that it is working correctly, add a test that verifies the score is set (0:0).

The above should work. However, I recommend going a step further and not inheriting from SoccerGame, which is presumably the class you are testing. While inheriting a test in this way is occasionally useful, it isn't the normal or the cleanest way to do it. It's better to separate your system under test from the tests themselves.

To do that, I suggest you instantiate a new SoccerGame for each test, doing so in the SetUp method. That will eliminate any possibility of state carrying over from one test to another since each test will use a new SoccerGame.

Upvotes: 0

Related Questions