单元测试抛出 NullReferenceException

Unit test throwing NullReferenceException

我一直在尝试 运行 测试从 xml 文件加载数据并将其作为列表 returns 的方法,但是,我不断收到 NullReferenceException当它 运行 时。我已经检查过,我的文件路径没问题。

[TestCase(1)]
public void firstTest(int num)
{
    var studentList = StudentListGenerator.CreateStudentList(@"../../TestReport/TestData.xml");

    Assert.IsTrue(studentList.Count() > num);
}

堆栈跟踪指向我的 CreateStudentList 方法中的一行代码,如果我将它直接插入测试本身,它就可以正常工作(当我 运行 它通常)。

String xData = File.ReadAllText(filePath);
var x = new XmlSerializer(typeof (Report));
Report dataConverted = (Report) x.Deserialize(new StringReader(xData)); 
// the last line is where the stack trace ends

有人猜到我哪里出错了吗?

编辑: 这是link到StudentListGeneratorclass的一部分,其中包含CreateStudentList方法:https://gist.github.com/jekrch/eecdd1c8de8a11268be0

这是完整的堆栈跟踪:

at PFdata.Dashboard.Data.StudentListGenerator.CreateStudentList(String filePath) in C:\Users\CodeCamp\Desktop\StudentDataDashboard\StudentDataDashboard\Dashboard.Data\StudentListGenerator.cs:line 41 at DashboardTests.StudentDataCalcTests.firstTest(Int32 num) in C:\Users\CodeCamp\Desktop\StudentDataDashboard\DashboardTests\StudentDataCalcTests.cs:line 22 Result Message: System.NullReferenceException : Object reference not set to an instance of an object.

所以原始错误的堆栈跟踪具有误导性。我正在测试的 CreateStudentList 方法中 NullReferenceException 的真正来源是以下行:

Application.Current.Properties["reportMonth"] = reportMonth;

问题是应用程序 class 没有被测试实例化。所以解决方案是像这样在测试开始时简单地实例化应用程序,

var app = new Application();

我从 comment by Ben Raupov 关于类似问题的问题中得到了尝试这个的想法。非常感谢 Unicorn2 帮助我排除了许多其他可能性。