【问题标题】:C# NUnit using TestCaseSource results in NullPointerC# NUnit 使用 TestCaseSource 导致 NullPointer
【发布时间】:2015-02-20 08:08:53
【问题描述】:

我有以下类,它是一个 TestFixture,它有一个测试和一个产生我的 TestCases 的 TestCaseSource。我的测试用例实际上包含实际结果和预期结果,它们被包装在一个名为 TestCaseEntity 的对象中

namespace SomeNamespace
{
    [TestFixture]
    public class MyTest
    {
        static Client client;
        static List<string> userIds = new List<string>();

        [TestFixtureSetUp]
        public void Init()
        {
            // Set up a client
            client = new Client("server address"); // a HTTP client

            // populate a List of userIds from a local text test file
            userIds.Add(GetAllIdsFromTxtFile());
        }

        [Test, TestCaseSource(typeof(MyTestCaseEntityFactory), "MyTestCases")]
        public void CheckExpectations(TestCaseEntity testCaseEntity)
        {
            if (!testCaseEntity.IsIdentical)
            {
                Log.Error("Log some shit");
                Assert.Fail("fail assertions");
            }
        }

        public class MyTestCaseEntityFactory
        {
            public static IEnumerable<TestCaseEntity> MyTestCases
            {
                get
                {
                    foreach (string id in userIds)
                    {
                        // use the client and get the results, construct the new TestCaseEntity(...) and return;
                        yield return new TestCaseEntity("actualValue", "expectedValue resulting from the server call");
                    }
                }
            }
        }
    }
}

当我运行我的测试时,我收到以下错误,很遗憾这不是很有帮助!

System.NullReferenceException : Object reference not set to an instance of an object.

关于我可能做错了什么有什么建议吗?

【问题讨论】:

  • 你能看一下异常堆栈跟踪和失败的行号吗?它通常更有帮助。

标签: c# nunit


【解决方案1】:

您在allSalesDEDealIds 上进行了 foreach,但您似乎没有将其包含在您的代码示例中。可能这是您代码中的NullRefException?

【讨论】:

  • 抱歉打错了,但这绝对不是问题所在。可以看到init方法执行成功了!
  • allSalesDEDealIds 方法在 init 方法之前被调用,因此您需要执行所有逻辑以在该方法中获取您的 id,即 userIds.Add(GetAllIdsFromTxtFile());必须在 allSalesDEDealIds 方法中调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多