gpt4 book ai didi

c# - TestContext.Properties 可用吗?

转载 作者:IT王子 更新时间:2023-10-29 04:50:04 27 4
gpt4 key购买 nike

使用 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 中没有明确记录。

在我看来,这是非常困惑的设计+实现。为什么要将 TestContext.Properties 作为一个集合呢?用户可以执行许多其他解决方案来进行类范围内的初始化。

最佳答案

TestContext 对于每个测试都是唯一的,因此在 ClassInitialize 中初始化它是行不通的。您应该只将它用于 TestInitialize、TestCleanup 和 TestMethod 方法。

This post很好地解释了一个类的测试是如何运行的,包括线程。

也就是说,我还没有找到 TestContext 的用途,但我是 MSTest 的新手。我同意 MSDN 文档令人困惑。让所有示例方法都写入控制台或抛出消息框并不能代表可能性。

关于c# - TestContext.Properties 可用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2517435/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com