Udostępnij za pośrednictwem


Test Class Inheritance is not working in the VS2010

If you have  a test class inheritance  and you using tfsbuild to build, you get the following error but it builds fine from IDE

UTA004: Illegal use of attribute on abc.Class1. The TestMethodAttribute can be defined only inside a class marked with the TestClass attribute.

  

The difference between the respective behaviors in VS and MSBuild is due to the way in which tests are discovered.  In 2008, the default in VS is to use the code model (CMI), which does not pick up the test method in the (non TestClass) base class.  When run from MSBuild, tests are discovered by reflecting on the test assembly.  It is a bug that these produce different results.

In 2010, CMI is turned off by default, and the test method in the base class will be discovered in both scenarios when reflecting on the assembly you will need to explicitly create a test method in each derived test class rather than having a single test method in the base class.  The common implementation can still be placed in the base class, but in a non-TestMethod.  I’ve included a simple example to illustrate the pattern below.

 

namespace TestProject
{
    public class UnitTestBase
    {
        protected void TestFooImpl()
        {
            Console.WriteLine("Foo ({0})", GetType().Name);
        }
    }

    [TestClass]
    public class UnitTest1 : UnitTestBase
    {
        [TestMethod]
        public void TestFoo()
        {
            TestFooImpl();
        }
    }

    [TestClass]
    public class UnitTest2 : UnitTestBase
    {
        [TestMethod]
        public void TestFoo()
        {
            TestFooImpl();
        }
    }
}

Comments

  • Anonymous
    August 09, 2010
    That is simply a maintenance nightmare..

  • Anonymous
    August 23, 2010
    I agree, having to create forwarding methods in the derived classes seriously impacts the benefit of inheritance.  Surely there is a better way!

  • Anonymous
    September 30, 2010
    The comment has been removed