【问题标题】:nunit TestContext throws NullReferenceExceptionnunit TestContext 抛出 NullReferenceException
【发布时间】:2013-04-15 12:16:45
【问题描述】:

我有以下代码:

[TestFixture]
public class LexicalTests
{
    [Test]
    public void LexicalTest1()
    {
        TestContext.CurrentContext.TestDirectory;
    }
}

CurrentContext 在尝试获取 TestDirectoryWorkingDirectory 属性时抛出异常。

我该如何解决这个问题?

P.S.:在我的家用 PC 上测试运行良好(没有奇怪的例外)。

【问题讨论】:

  • 我看到stackoverflow上有一些类似的问题,但我找不到答案。
  • 我无法重现这种行为。您使用的是哪个版本的 NUnit?你是如何运行测试的?您是否有任何其他链接的库也可能使用 TestContext 作为对象名称?其他单元测试是否正确运行?你能发布失败的单元测试的确切代码吗?
  • 我使用带有 Resharper 单元测试 UI 的 nunit 2.6.2...我发现当我使用 nunit.exe 时测试通过了
  • 这很奇怪,因为我使用了带有 NUnit 2.6.2 的 Resharper 测试运行器,它对我有用。我正在使用 Resharper 7,您使用的是哪个版本?我的传递代码只是包装了这一行: Assert.IsNotNull(TestContext.CurrentContext.TestDirectory);

标签: c# unit-testing nunit resharper


【解决方案1】:

似乎某些提供运行 NUnit 单元测试功能的应用程序的 TestContext 类存在问题。

下面类中的测试应该通过:

using NUnit.Framework;

namespace UnitTests
{
    [TestFixture]
    public class UnitTests
    {
        [Test]
        public void CurrentContextTest()
        {
            Assert.IsNotNull(TestContext.CurrentContext);
            Assert.IsNotNull(TestContext.CurrentContext.TestDirectory);
            Assert.IsNotNull(TestContext.CurrentContext.WorkDirectory);
        }
    }
}

如果测试没有通过,那么正如 Dmitry 在上面的评论中所写,在 ReSharper 菜单中更改 NUnit 版本。在 Visual Studio 中,转到 ReSharper -> 选项 -> 工具 -> NUnit。单击指定的 NUnit 安装单选按钮并确保指定了包含 nunit.core.dll、nunit.core.interfaces.dll 和 nunit.util.dll 的文件夹。如果找不到列出的文件,则会显示错误。

一旦 NUnit 版本被更改,重新运行测试,它应该可以通过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 2020-11-17
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多