locked
Inheritance in MS unit test class RRS feed

  • Question

  • Hello Sir/Madam,

    I am using Native C++ language MS Test project and I want to inherit the newly created MS test class with some base class.

    How can I achieve it?

    lets say, I have a below class

    Class Base

    {

    .....

    }

    TEST_CLASS(UnitTest1) : public Base

    {

    ....

    }

    I want to inherit the Base class in my MS unit test class.

    Is there is way to achieve this? Is there any alternatives?

    Thanks!

    Puneet

    Tuesday, March 15, 2016 1:03 PM

All replies

  • Hi Puneet,

    Thanks for your post.

    As far as I know. Inheritance is not supported for Unit Tests.

    In order to make your tests inherit from a base class test, may be you can try like this,

    public class MyBaseClass
    {
        public virtual void DoStuff() { }
        public virtual void DoOtherStuff() { }
    }
    
    public class MySubClass : MyBaseClass
    {
        public override void DoOtherStuff()
        {
            // different to to base
        }
    }
    
    public abstract class TestOfBaseClass
    {
        protected abstract MyBaseClass classUnderTest { get; }
    
        [TestMethod]
        public void TestDoStuff()
        {
            classUnderTest.DoStuff();
            Assert.StuffWasDone();
        }
    }
    
    [TestClass]
    public class WhenSubclassDoesStuff : TestOfBaseClass
    {
        protected override MyBaseClass classUnderTest
        {
            get { return new MySubClass(); }
        }
    
        [TestMethod]
        public void ShoudDoOtherStuff()
        {
            classUnderTest.DoOtherStuff();
            Assert.OtherStuffDone();
        }
    }

    Best Regards,

    Lake Xiao


    • Edited by lake Xiao Wednesday, March 16, 2016 2:54 AM
    • Proposed as answer by lake Xiao Wednesday, March 23, 2016 6:00 AM
    Wednesday, March 16, 2016 2:53 AM
  • But MS unit Test uses some Macros like TEST_CLASS..Can you provide me an example using it?
    Wednesday, March 16, 2016 5:59 AM
  • Hi Puneet,

    Please take a look at  the reply shared by eremy in the following thread :

    http://stackoverflow.com/questions/13862910/unit-testing-methods-created-by-a-macro

    Best Regards,

    Lake Xiao

    Thursday, March 17, 2016 7:37 AM