简体   繁体   English

我们可以对所有单元测试类仅使用一个ClassInitialize吗?

[英]Could we use only one ClassInitialize for all the Unit Testing classes?

I started an internship where my job consists of seting up unit tests on some projects. 我开始实习,我的工作包括在某些项目上设置单元测试。

I have already implemented dozens of tests and now I want to create a mechanism which restores the original database after or before each run. 我已经实现了几十个测试,现在我想创建一种在每次运行之后或之前恢复原始数据库的机制。

I have the necessary scripts to create, populate and drop my database, but I don't want to call this mechanism each test classes, but instead call it just once. 我具有创建,填充和删除数据库的必要脚本,但是我不想在每个测试类中都调用此机制,而是只调用一次。

Is it possible to create a ClassIniatialize() who is called only once when I start one or all the tests? 是否可以创建一个ClassIniatialize() ,当我启动一个或所有测试时, ClassIniatialize()仅被调用一次?

EDIT 编辑

All I/you need is to use AssemblyInitialize() and AssemblyCleanUp() and all is resolved, ;) 我/您所需要做的就是使用AssemblyInitialize()AssemblyCleanUp() ,所有这些都将解决;;)

我/您所需要做的就是使用AssemblyInitialize()AssemblyCleanUp() ,所有这些都将解决;;)

You could start a transaction on TestInitialize and do a rollback on TestCleanup . 你可以开始交易TestInitialize并做回滚TestCleanup This approach would allow you to avoid data changes to perdure outside the scope of individual tests. 这种方法将使您避免在单个测试范围之外的数据更改。

  [TestInitialize()]
  public void Initialize()
  {
     //Init DB Transaction
  }

  [TestCleanup()]
  public void Cleanup()
  {
     //Rollback DB Transaction, database returns to the initial state
  }

You'll need to have a previously populated test database to run test on. 您需要具有先前填充的测试数据库才能对其进行测试。

As a side note, database access should be tested on integration test and not on unit test. 附带说明,应在集成测试而非单元测试上测试数据库访问。 Adding external dependencies is against unit test definition. 添加外部依赖项违反了单元测试的定义。

Check also about the possibility of using in memory SQLite , will be more suitable for testing database access that a production db engine. 还检查一下在内存中使用SQLite的可能性,将更适合于测试生产db引擎的数据库访问。

You could create a base class and decorate a method in that base class with the ClassInitialize-attribute. 您可以创建一个基类,并使用ClassInitialize-attribute在该基类中装饰一个方法。

After that you just need to make sure that all your test-classes inherit from this base class. 之后,您只需要确保所有测试类都从该基类继承即可。

ClassInitilize method will be called once for every testclass you have. 对于每个测试类,ClassInitilize方法将被调用一次。 You may implement it just once in a base testclass for example, but it will still be called once for every test class. 例如,您可以在基本测试类中仅实现一次,但是仍然会为每个测试类调用一次。

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

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