MsTest ClassInitialize and Inheritance

后端 未结 4 1134
小鲜肉
小鲜肉 2020-12-05 12:17

I have a base class for my tests which is composed in the following way:

[TestClass]
public abstract class MyBaseTest
{
   protected static string myField =          


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 13:01

    UPDATE: Added lock to avoid multi-threading issues...

    We know that a new instance of the class is constructed for every [TestMethod] in the class as it gets run. The parameter-less constructor of the base class will be called each time this happens. Couldn't you simply create a static variable in the base class and test it when constructor runs?

    This helps you to not forget to put the initialization code in the sub-class.

    Not sure if there's any drawback to this approach...

    Like so:

    public class TestBase
    {
        private static bool _isInitialized = false;
        private object _locker = new object();
    
        public TestBase()
        {
            lock (_locker) 
            {
              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()
        {
        }
    }
    

提交回复
热议问题