开发者

What's the difference between using the constructor in VS Testing framework vs. TestInitialize() attribute?

Quick question, I'm using the Visual Studio's testing framework for unit testing. Just wondering what's the difference开发者_C百科 between using the constructor to do initialization work vs. having a method with [TestInitialize()] attribute?


This post gives an overview of the different methods. As you can see, the ctor is called immediately before the ClassInitialize (only once, of course) and TestInitialize.

So put stuff that requires code in ClassInitialize in your TestInitialize method. Everything that should be set up before ClassInitialize goes in the ctor.

Obviously, TestInitialize content will be executed once before each test. The corresponding method to close after each test is TestCleanup. For classes, use ClassCleanup. The same thing exists for assemblies as well (AssemblyInitialize/Cleanup).

Further reading


Conceptually they are they same, as MSTest creates a new instance of your test class before each test execution. However, technically there are a few differences:

  1. The ctor is called before TestInitialize (no surprise as the latter is an instance method).
  2. You have access to TestContext in TestInitialize.
  3. More inheritance scenarios are enabled with TestInitialize: https://stackoverflow.com/a/8689398/67824.
  4. You can assign readonly fields in the ctor. I think it's pretty important: https://stackoverflow.com/a/45270180/67824.


The ctor is for initializing the object.

TestInitialize is for initializing any objects or data needed to run the test.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜