MsTest ClassInitialize and Inheritance

I have a base class for my tests, which is composed as follows:

[TestClass] public abstract class MyBaseTest { protected static string myField = ""; [ClassInitialize] public static void ClassInitialize(TestContext context) { // static field initialization myField = "new value"; } } 

Now I'm trying to create a new test that inherits from the database, with the following signature:

 [TestClass] public class MyTest : MyBaseTest { [TestMethod] public void BaseMethod_ShouldHave_FieldInitialized() { Assert.IsTrue(myField == "new value"); } } 

ClassInitialize never called by child tests ... What is the real and correct way to use test initialization with inheritance on MsTest?

+57
c # mstest
Apr 11 '13 at 8:54
source share
4 answers

Unfortunately, you cannot achieve this because the ClassInitializeAttribute Class cannot be inherited.

An inherited attribute can be used by subclasses of classes that use it. Because ClassInitializeAttribute cannot be inherited when the MyTest class MyTest initialized, the ClassInitialize method from the MyBaseTest class cannot be called.

Try to solve it differently. A less efficient way is to define the ClassInitialize method in MyTest and just call the base method instead of duplicating the code.

+35
Apr 11 '13 at 10:12
source share

A potential workaround is to define a new class with AssemblyInitializeAttribute . Obviously, it has a different scope, but for me it meets my needs (cross-cutting issues, which just like that, require the same settings for each test class and test method.)

 using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MyTests { [TestClass] public sealed class TestAssemblyInitialize { [AssemblyInitialize] public static void Initialize(TestContext context) { ... } } } 
+5
Jun 18 '16 at 17:22
source share

We know that a new instance of the class is created for each [TestMethod] in the class as it starts. Each time this happens, a constructor without parameters will be called. Could you just create a static variable in the base class and check it when the constructor starts?

This will help you remember to place the initialization code in a subclass.

Not sure if there is a flaw in this approach ...

Same:

 public class TestBase { private static bool _isInitialized = false; public TestBase() { if (!_isInitialized) { TestClassInitialize(); _isInitialized = true; } } public void TestClassInitialize() { // Do one-time init stuff } } public class SalesOrderTotals_Test : TestBase { [TestMethod] public void TotalsCalulateWhenThereIsNoSalesTax() { } [TestMethod] public void TotalsCalulateWhenThereIsSalesTax() { } } 
0
Jan 22 '15 at
source share

Use static constructor for base class? This is done only once, by design, and it does not have a strange inheritance restriction like ClassInitializeAttribute.

0
Jun 17 '19 at 15:06
source share



All Articles