我一定是疯了,因为我的单元测试失败了,因为以下代码抛出了空引用异常:
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
导致此错误的代码行是:
pid = parentCategory.Id;
console.writeline仅用于在NUnit GUI中进行调试,但它输出一个有效的int。
编辑:它是单线程的,因此无法从其他线程分配为null,并且Console.WriteLine成功打印出值表明它不应该抛出异常。
编辑:类别类的相关片段:
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
如果任何人想查看完整的代码,可以在Google Code上查看:http://code.google.com/p/chefbook/source/checkout
我觉得我要尝试重新启动电脑......我看到一些比较奇怪的问题通过重新启动解决了。重启后会更新。
更新:谜团解开了。看起来NUnit将错误行显示为最后一个成功执行的语句......将测试复制/粘贴到新的控制台应用程序中并在VS中运行,显示if语句块之后的行(未显示)包含空引用。感谢大家提供的所有想法。+1给所有回答的人。