I’m trying to set up unit tests for a card game application, but my code is throwing a NullReferenceException: Object reference not set to an instance of an object. As far as I can tell I should not be getting this error, but there it is.
Here is my code:
[TestFixture]
public class Tests
{
CardTable aTable = null;
[SetUp]
public void setup()
{
aTable = new CardTable();
}
[Test]
public void setPlayerGold_setTo0_return0()
{
//arrange
//act
aTable.setPlayerGold(0);
//assert
Assert.AreEqual(0, aTable.playerGold);
}
}
public class CardTable
{
int playerGold;
public CardTable()
{
playerGold = 0;
}
public void setPlayerGold(int amount)
{
if (amount == 0)
{
playerGold = 0;
}
else
{
playerGold += amount;
}
goldLabel.Text = playerGold + "";
}
The exception gets thrown at the aTable.setup line as though aTable was not instantiated, even though it clearly was in the [Setup], and I can’t figure out why. When I remove the ‘act’ call, the test passes, so aTable cannot be null or the test would fail there as well.
I am running Visual C# 2010 Express v10.0.40219.1 SP1Rel with NUnit 2.6.0.12051.
Any help would be appreciated.
Thanks!
I believe it’s in the goldLabel.Text You aren’t instantiating a form anywhere, so the controls on the form are null.
As a general rule, you probably don’t want to test that a label is set to a value in your unit tests, instead somehow mock this object or just write a test that a value is set (but not that a label’s text is updated.)