-2

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

  • Change the static variable to be a property with getter and setter. Have the setter throw an exception (whenever you want to detect invalid modification. – mjwills Jul 29 '19 at 11:06
  • sorry that is the idea i had to fix it, i can't really do what you surgest as i'm not allowed to modify that part as part main branch, but otherwise good surgestion – user3406087 Jul 29 '19 at 11:11
  • i was hoping that there was some way to mark a test case as first, that create a duplicate of the variable and then mark another that runs last, that could compare the two. i have a methode for creating a clean copy and another that can do a complete compare – user3406087 Jul 29 '19 at 11:18
  • https://stackoverflow.com/questions/2255284/how-does-mstest-determine-the-order-in-which-to-run-test-methods – mjwills Jul 29 '19 at 11:24
  • Those unit tests are bad designed. They must not depend on an external dependency that is not set in the test itself, like your "static variables". You should find and rewrite those tests. – JotaBe Jul 29 '19 at 11:59

1 Answers1

0

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

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • that could work, but is there anyway where i don't have to modify all classes to contain these checks? i have well over 100 – user3406087 Jul 29 '19 at 11:54