使用Visual Studio生成Test Unit类.然后注释,类初始化方法.在里面使用testContext参数添加你的属性.
在测试app启动时,测试基础架构确实调用了此方法.
//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
}
Run Code Online (Sandbox Code Playgroud)
离开MyClassInitialize后,用户添加的任何属性都将丢失.只剩下10个"官方"的.
实际上,每次调用每个测试方法之前,TestContext都会被初始官方文件覆盖.它只有在用户有测试初始化方法时才会被覆盖,在那里进行的更改都会传递给测试.
//Use TestInitialize to run code before running each test
[TestInitialize()]public void MyTestInitialize(){
this.TestContext.Properties.Add("this is preserved",1) ;
}
Run Code Online (Sandbox Code Playgroud)
这实际上意味着TestContext.Properties对于用户来说"大部分"只读.这在MSDN中没有明确记录.
在我看来,这是非常凌乱的设计+实现.为什么要将TestContext.Properties作为集合呢?用户可以使用许多其他解决方案进行类范围的初始化.
小智 1
我相信您必须保留 testContext 的副本,否则它将超出范围。
我补充道:
private TestContext _tc;
Run Code Online (Sandbox Code Playgroud)
并添加到初始化
tc = testContext;
Run Code Online (Sandbox Code Playgroud)
当我从其中一项测试中查看 tc 时,它包含新添加的属性。