问题
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.
I am running Visual C# 2010 Express v10.0.40219.1 SP1Rel with NUnit 2.6.0.12051.
Any help would be appreciated. Thanks!
回答1:
Start NUnit, but don't run the tests. In visual studio make sure you have the project that contains your nunit tests open. Then in visual studio press ctrl+alt+p. This will bring up the list of processes to attach to. Choose the nunit-agent.exe process. If there is more than one nunit-agent.exe process you can ctrl+ to choose all of them. You may have to check the Show processes in all sessions and/or Show processes from all users to get the nunit-agent.exe to show up. At this point you should be able to debug your test.
Now you can set a breakpoint at the constructor call to CardTable
. As you step through the debugger you should be able to identify your null object reference error.
An alternative to stepping through the code is to choose in the menu Debug->Exceptions... in the dialog that shows check the thrown box next to Common Language Runtime Exceptions. This will cause the debugger to stop on any execptions handled or unhandled when they are thrown. This removes the need for the breakpoint, but if you have exceptions being thrown that are caught, it may be more hassle than the breakpoint method above.
回答2:
It looks like setup is your problem, and it isn't being called when you want it to.
I recommend doing this:
CardTable aTable = new CardTable();
That way it won't ever be null.
回答3:
I had the same problem and i have rolled back NUnit framework version from 3.7.1 to 3.0.5 and now all works without exceptions. Maybe you should roll back to one of the previous version of NUnit framework.
来源:https://stackoverflow.com/questions/10481787/nullreferenceexception-when-using-nunit