C# 标有 TestInitialize 和 TestCleanup 的类未执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12520759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Classes marked with TestInitialize and TestCleanup not executing
提问by Stefan de Kok
I have been struggling with this one, hopefully it will help someone else.
我一直在努力解决这个问题,希望它能帮助别人。
Whilst creating unit tests using MsTest I discovered I was repeating the same code in each test, and found a couple of handy attributes (TestInitialize, TestCleanup, ClassInitialize, and ClassCleanup).
虽然使用创建单元测试MSTEST我发现我在每个测试重复相同的码,并发现了几个方便的属性(TestInitialize,TestCleanup,ClassInitialize,和ClassCleanup)。
Supposedly, when you mark a method with one of these attributes, it should execute automatically (prior to each test, after each test, prior to all tests, and after all tests respectively). Frustratingly, this did not happen, and my tests failed. If directly calling these methods from the classes marked with TestMethodattribute, the tests succeeded. It was apparent they weren't executing by themselves.
假设,当您使用这些属性之一标记方法时,它应该自动执行(分别在每个测试之前、每个测试之后、所有测试之前和所有测试之后)。令人沮丧的是,这并没有发生,我的测试失败了。如果直接从标有TestMethod属性的类中调用这些方法,则测试成功。很明显,他们不是自己执行的。
Here is some sample code I was using:
这是我使用的一些示例代码:
[TestInitialize()]
private void Setup()
{
_factory = new Factory();
_factory.Start();
}
So why is this not executing?
那么为什么这不执行呢?
采纳答案by Stefan de Kok
The trick is to make these methods public:
诀窍是使这些方法public:
[TestInitialize()]
public void Setup()
{
_factory = new Factory();
_factory.Start();
}
When they are privatethey do not execute.
当它们存在时,private它们不会执行。
回答by Stefan de Kok
TestInitialize and TestCleanup are run before and after all the tests, not before and after each one.
TestInitialize 和 TestCleanup 在所有测试之前和之后运行,而不是在每个测试之前和之后运行。
That is wrong, see for example this link: http://social.msdn.microsoft.com/Forums/en-US/vststest/thread/85fb6549-cbaa-4dbf-bc3c-ddf1e4651bcf
这是错误的,例如参见此链接:http: //social.msdn.microsoft.com/Forums/en-US/vststest/thread/85fb6549-cbaa-4dbf-bc3c-ddf1e4651bcf
See also MSDN
另见 MSDN
The example code shows how to use TestInitialize, ClassInitialize, and AssemblyInitialize.
示例代码显示了如何使用 TestInitialize、ClassInitialize 和 AssemblyInitialize。
回答by Nadine
I also had the problem and - due to my misunderstanding of how the methods get called - solved it with this: Make your tests inherit from the class containing the TestInitialize and TestCleanup methods.
我也遇到了这个问题,并且 - 由于我对如何调用方法的误解 - 解决了这个问题:使您的测试从包含 TestInitialize 和 TestCleanup 方法的类继承。

