Search code examples
c#mstest

How do i check if Static variables are modified during unittest


I'm working with a rather large test set (over 5000 seperate test methodes) and it apears that some test sometimes modify static variables that they shouldn't, so i was wondering if there was a way to create a test that tests if a variable has been modified, during all the other tests

i'm unable to modify the variables directly but i can write unit test and modify the settings pertaining there to

i'm working in VS 2017 with C# 8.0 and mstest v.2

thanks


Solution

  • You can mark methods in your test class to run before or after each test.

    So you can do something like this:

    [TestClass]
    public class MyTestClass
    {
       private int originalValue; // adjust the type as needed
    
       [TestInitialize]
       public void PreTest()
       {
          // remember the value before the test
          originalValue = MyContainer.StaticValue; // or whatever it is called in your system
       }
    
       [TestCleanup]
       public void PostTest()
       {
          // check the current value against the remembered original one
         if (MyContainer.StaticValue != originalValue)
         {
            throw new InvalidOperationException($"Value was modified from {originalValue} to {MyContainer.StaticValue}!");
         }
       }
    
       [TestMethod]
       public void ExecuteTheTest()
       {
          // ...
       }
    }
    

    For other attributes, see a cheatsheet