Search code examples
c#mstest

How to organize TestClass to show in TestExplorer multiple times, once per each parameter?


I have MSTest [TestClass] class with 15 test methods [TestMethod]. Test class tests “local” and “remote” storages. Using Visual Studio22’s TestExplorer I would like to see “LocalStorage” tests and “RemoteStorage” tests separately.

Each instance should have two parameters: StorageType and DefaultFolder, that are set up per storage type

How can I achieve that?


Solution

  • Create a base class with the test methods. Don't mark it as TestClass. Then inherit classes marked as TestClass that set properties of the base class in their initialize method that control behaviour.

    // base class with test methods
    public class BaseStorageTest
    {
        protected string defaultFolder;
        protected bool remoteStorage;
    
        [TestMethod]
        public void TestMethod1()
        {
            if (remoteStorage)
            {
                Assert.Fail("Failing remote");
            }
        }
    
        [TestMethod]
        public void TestMethod2()
        {
        }
    
        [TestMethod]
        public void TestMethod3()
        {
        }
    }
    
    // Initialize for local test
    [TestClass]
    public class LocalStorageTest : BaseStorageTest
    {
        [TestInitialize]
        public void Initialize()
        {
            remoteStorage = false;
            defaultFolder = "....";
        }
    }
    
    // Initialize for remote test
    [TestClass]
    public class RemoteStorageTest : BaseStorageTest
    {
        [TestInitialize]
        public void Initialize()
        {
            remoteStorage = true;
            defaultFolder = "....";
        }
    }
    

    enter image description here