c# - TestContext 名称与给定代码有何关联?

标签 c# visual-studio unit-testing mstest

我正在使用 MicrosoftTestTools。我有一个包含 [TestMethod] 和 [ClassInitialize] 的 A 类。

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
    Setup(context);
}

Setup 的定义存在于 B 类(A 类的基类)中。

   public static void Setup(TestContext context)
    {
something
    }

[TestCleanUp] 出现在 B 类中。

[TestCleanup]
public void TestCleanUp()
{    
        if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed){}

}

为了在 TestCleanUp 方法中获取 TestContext,我在类 B 中创建了如下所示的属性。

public TestContext TestContext { get; set; }

它运行良好。但是当我像这样更改声明时,

public `TestContext CurrentContext{ get; set; }`

所以功能像

[TestCleanup]
public void TestCleanUp()
{ 
if (CurrentContext.CurrentTestOutcome == UnitTestOutcome.Failed){}
}

CurrentContext 为空。这里的属性(property)如何运作?这仅在名称为 TestContext 时有效。我对 C# 编程很天真。

最佳答案

您可能已经注意到您没有自己分配 TestContext 属性,但是它以某种方式获得了它的值。它如何获得值(value)?测试框架分配它。它如何找到该属性?它查找类型为 TestContext 的名为 TestContext 的属性。因此,当您更改名称时 - 它无法再找到它并且无法分配值,因此它保持为空。

您可以在 documentation 中阅读有关此类的更多信息.这个问题的相关部分是:

When you run a unit test, you are automatically provided with a concrete instance of the TestContext type, if the test class that contains your unit test method has a TestContext property defined.

关于c# - TestContext 名称与给定代码有何关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508887/

相关文章:

vb.net - 使用条码扫描仪时未显示 MsgBox

在 CPP 文件 (Visual Studio) 中实现的 C++ 模板错误

c# - 无法使用 ConfigurationManager 在 C# .NET Core 单元测试项目中读取 app.config

ios - 将 OCMock 与未知数量的方法调用一起使用

c# - 在 C++/CLI 中实现 C# 接口(interface)函数返回数组

c# - 如何使用 dateTimePicker 将日期插入 SQL 数据库日期列?

c# - 是否应将所有对象解耦

c# - Linq to XML - 将多个元素合并为一个类

visual-studio - 如何折叠所有不会在 Visual Studio 中编译的#ifdefs block ?

reactjs - jsdom:无法读取 null 的属性 '_location'