什么是C#单元测试的生命周期 [英] What's the life cycle of Unit Tests in C#

查看:113
本文介绍了什么是C#单元测试的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual Studio(Ctrl + R,A)中的C#中,完整的 MSTest 单元测试运行中的事件顺序是什么?

What's the sequence of events in a full MSTest run of unit tests in C# inside Visual Studio (Ctrl+R, A)?

这是我到目前为止的想法:

Here's what I think so far:

  • 1-运行[AssemblyInitialize]
  • 2-随机运行[ClassInitialize]
  • 3-运行类[TestInitialize]
  • 4-从该类中随机运行[TestMethod]
  • 5-运行类[TestCleanup]
  • 为类中的每个TestMethod重复3到5
  • 为每个测试类别重复2到5
  • 6-运行所有类[ClassCleanup]方法
  • 7-运行[AssemblyCleanup]
  • 1 - Runs [AssemblyInitialize]
  • 2 - Randomly runs a [ClassInitialize]
  • 3 - Runs the class [TestInitialize]
  • 4 - Randomly runs a [TestMethod] from that class
  • 5 - Runs the class [TestCleanup]
  • Repeat 3 through 5 for each TestMethod in the class
  • Repeat 2 through 5 for each test class
  • 6 - Runs all classes [ClassCleanup] methods
  • 7 - Runs [AssemblyCleanup]

但是我认为VS可能会立即初始化多个类,然后随机运行TestMethods.测试应该在整个类中还是在整个测试项目甚至整个解决方案中都是自治的?知道事件的确切顺序应该回答这些问题.

But I think VS might initialize multiple classes at once and then randomly run TestMethods. Should the tests be autonomous across its class or across the whole test project, or even the whole solution? Knowing the exact sequence of events should answer those questions.

更新:

我做了一些测试,发现确实是事件发生的顺序,除了#3到5可以运行ANY类的任何测试. Visual Studio似乎一次顺序运行一个测试.但是,出于已接受的答案中所述的原因,不应依赖于此.

I did some tests and found that it is indeed the order in which events occurs, except for #3 to 5 where ANY test from ANY class could run. Visual Studio seems to sequentially run one test at a time. However, one should not rely on this for reasons explained in accepted answer.

推荐答案

您是正确的.这确实是代码运行的顺序.但是,由于测试应该是完全独立的,因此不能保证测试将按顺序运行,并且不能在单个线程上运行.该框架可以同时运行多个测试.

You are correct. This is indeed the order in which the code will be run. However, since tests should be completely independent, there are no guarantee that they will be run in order and that they will be run on a single thread. The framework could run multiple test at the same time.

如果需要,您也可以通过使用测试用例来强制执行特定的测试命令,但这被认为是不好的做法,因为应该使用测试用例将测试重新组合在一起(对它们进行标记).

You can force a specific test order through the use of test cases if you need too, but this is considered bad practice as test cases should be used to regroup tests together (tag them) instead.

这篇关于什么是C#单元测试的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆