本文介绍了在使用的NullReferenceException NUnit的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图设立一个纸牌游戏应用程序的单元测试,但我的代码是抛出一个NullReferenceException:未将对象引用设置到对象的实例。至于我可以告诉我不应该得到这个错误,但它是。

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.

下面是我的代码:

        [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没有实例,尽管它显然是在[设置],我想不通为什么。

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.

我正在运行的Visual C#2010速成v10.0.40219.1 SP1Rel与NUnit的2.6.0.12051。

I am running Visual C# 2010 Express v10.0.40219.1 SP1Rel with NUnit 2.6.0.12051.

任何帮助,将不胜感激。
谢谢!

Any help would be appreciated.Thanks!

推荐答案

它看起来像设置是你的问题,它不会被调用,当你想它。到

It looks like setup is your problem, and it isn't being called when you want it to.

我建议这样做:

CardTable aTable = new CardTable();



这样,它永远不会为null。

That way it won't ever be null.

这篇关于在使用的NullReferenceException NUnit的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 22:40