使用Visual Studio生成测试单元类。然后在类初始化方法中进行注释。在其中使用testContext参数添加您的属性。
在测试应用程序启动时,测试基础设施确实会调用此方法。
//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
/*
* Any user defined testContext.Properties
* added here will be erased after this method exits
*/
testContext.Properties.Add("key", 1 ) ; // place the break point here
}
离开MyClassInitialize后,用户添加的所有属性都会丢失。只剩下10个“官方”的了。
实际上,每次调用每个测试方法之前,TestContext都会被覆盖,并使用最初的官方方法。如果只有当用户有测试初始化方法时才覆盖它,则在那里所做的更改将传递给测试。
//Use TestInitialize to run code before running each test
[TestInitialize()]public void MyTestInitialize(){
this.TestContext.Properties.Add("this is preserved",1) ;
}
这实际上意味着TestContext.Properties对用户来说“大部分”是只读的。这在MSDN中没有清楚地记录。
在我看来,这是一个非常混乱的design+implementation。为什么要把TestContext.Properties作为一个集合呢?用户可以做许多其他的解决方案来实现类范围的初始化。
发布于 2010-04-07 23:06:09
对于每个测试,TestContext都是唯一的,因此在ClassInitialize中初始化它将不起作用。您应该只对TestInitialize、TestCleanup和TestMethod方法使用它。
This post很好地解释了来自一个类的测试是如何运行的,包括线程。
话虽如此,我还没有发现TestContext的用法,但我是MSTest的新手。我同意MSDN文档令人困惑。将所有示例方法写入控制台或抛出消息框并不能表示可能性。
发布于 2010-03-26 02:27:48
我相信您必须持久化testContext的副本,否则它将退出范围。
我补充道:
private TestContext _tc;
并添加到Initialize
tc = testContext;
当我从一个测试中查看tc时,它包含了新添加的属性。
发布于 2017-02-21 08:49:37
TestContext用于将信息从外部传递到测试中。通过测试执行器或.runsettings文件,因此它的数据通常是单向的。
https://stackoverflow.com/questions/2517435
复制相似问题