简体   繁体   English

为什么ClassCleanup属性需要在静态方法上?

[英]Why does the ClassCleanup Attribute need to be on a static method?

Background: I have a bunch of unit tests in .NET that require some configuration data to be set up in order to run. 背景:我在.NET中有一堆单元测试,需要设置一些配置数据才能运行。 Initially, I was using TestInitialize and TestCleanup to set up and tear down the configuration data around each test; 最初,我使用TestInitializeTestCleanup来设置和拆除每个测试周围的配置数据; however, a single setup is sufficient for the entire suite of tests, so I would prefer to use ClassInitialize and ClassCleanup instead. 但是,对于整个测试套件来说,单个设置就足够了,所以我宁愿使用ClassInitializeClassCleanup

Problem: When I change the attribute from TestInitialize to ClassInitialize and run the tests, I get the following error: 问题:当我将属性从TestInitialize更改为ClassInitialize并运行测试时,我收到以下错误:

MyTestClass.ClassInit has wrong signature. MyTestClass.ClassInit有错误的签名。 The method should be marked static. 该方法应标记为静态。

What are the design reasons behind this attribute requiring its method to be static? 这个属性背后的设计原因是什么,要求它的方法是静态的? All of my test methods are instance methods, so I would assume there's at least one instance of my test class being created somewhere in order to run them. 我的所有测试方法都是实例方法,所以我假设我的测试类至少有一个实例是在某处创建的,以便运行它们。 Why would that instance not be in charge of cleaning up afterward? 为什么那个实例后来不负责清理呢?

I did check MSDN , and they don't explicitly mention the static requirement, although they do have a good example of its usage. 我确实检查了MSDN ,他们没有明确提到静态要求,尽管他们确实有一个很好的例子。

As MSDN states the ClassInitializeAttribute 由于MSDN声明了ClassInitializeAttribute

Identifies a method that contains code that must be used before any of the tests in the test class have run and to allocate resources to be used by the test class. 标识一种方法,该方法包含在测试类中的任何测试运行之前必须使用的代码,并分配要由测试类使用的资源。 This class cannot be inherited. 这个类不能被继承。

one example that I can think about where this can come in hand, is when you have a static field in your class that the constructor of the instances depends on. 我可以考虑的一个例子就是当你的类中有一个静态字段时,实例的构造函数依赖于它。

class foo
{
  static someObject bar;
  int foobar;

  public foo()
  {
    this.foobar = foo.bar.SomeMethod()
  }
}

this way in your ClassInitializeAttribute method you can assign a value to the static bar object, which will effect all the instances created later on. 这样,在ClassInitializeAttribute方法中,您可以为静态bar对象赋值,这将影响稍后创建的所有实例。

Another case you might want to use the ClassInitializeAttribute is for assigning global objects that the test might use (such as a mock database etc.) 您可能希望使用ClassInitializeAttribute另一种情况是分配测试可能使用的全局对象(例如模拟数据库等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM