我正在尝试为纸牌游戏应用程序设置单元测试,但是我的代码抛出了NullReferenceException:未将对象引用设置为对象的实例。据我所知,我不应该得到这个错误,但它确实存在。
这是我的代码:
[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 + "";
}
异常会在aTable.setup行抛出,好像aTable没有实例化,即使它显然在[Setup]中,我也无法找出原因。当我删除'act'调用时,测试通过,因此aTable 不能为null或测试也会失败。
我正在使用NUnit 2.6.0.12051运行Visual C#2010 Express v10.0.40219.1 SP1Rel。
任何帮助将不胜感激。 谢谢!
答案 0 :(得分:1)
您可能还想在Assert.AreEqual(0, aTable.playerGold);
中更改您的值以使用get方法,而不是直接引用objects属性。
类似
aTable.getPlayerGold()
答案 1 :(得分:0)
我相信它在goldLabel.Text中你没有在任何地方实例化一个表单,所以表单上的控件都是null。
作为一般规则,您可能不想测试标签是否设置为单元测试中的值,而是以某种方式模拟此对象或只是编写一个值设置的测试(但不是标签的文字已更新。)