Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend the .NET TestClass

Tags:

c#

.net

I am trying to extend the .NET TestClass. I found out that I need to extend the following abstract classes: TestClassExtensionAttribute and TestExtensionExecution. TestExtensionExecution also requires me to implement an ITestMethodInvoker. I have done the following but when I run a test method none of my breakpoints are being hit (neither in the test nor the extensions), meaning the test class never gets to my extension and obviously fails at an earlier point. Could somebody point me at what I am missing or at a working example for how to extend the TestClass?

Extension:

class CoreTestClass : TestClassExtensionAttribute
{
    public override Uri ExtensionId
    {
        get { throw new NotImplementedException(); }
    }

    public override TestExtensionExecution GetExecution()
    {
        return new TestCore();
    }
}

class TestCore: TestExtensionExecution
{
    public override ITestMethodInvoker CreateTestMethodInvoker(TestMethodInvokerContext context)
    {
        return new AnalysisTestMethodInvoker();
    }

    public override void Dispose()
    {

    }

    public override void Initialize(TestExecution execution)
    {
        execution.OnTestStopping += execution_OnTestStopping;
    }

    void execution_OnTestStopping(object sender, OnTestStoppingEventArgs e)
    {
        throw new NotImplementedException();
    }
}

class AnalysisTestMethodInvoker : ITestMethodInvoker
{
    public TestMethodInvokerResult Invoke(params object[] parameters)
    {
        throw new NotImplementedException();
    }
}

Test:

[CoreTestClass]
public class HomeControllerTest
{
    [TestMethod]
    public void Index()
    {
        // Arrange
        HomeController controller = new HomeController();

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        Assert.AreEqual("Modify this template to jump-start your ASP.NET MVC application.", result.ViewBag.Message);
    }
}
like image 882
Konstantin Dinev Avatar asked Oct 20 '22 22:10

Konstantin Dinev


1 Answers

This MSDN article describes how to implement TestClassExtensionAttribute: Extending the Visual Studio unit test type

Related question: Is defining TestMethod's in test base classes not supported by MsTest?

Depending on what you are tyring to accomplish you can use a standard abstract class marked with [TestClass]. TestClassAttribute will be inherited by derived types, however derived types must also be marked with [TestClass] for use with [TestInitialize] and [TestCleanup].

See Using a base class for your unit testing classes.

like image 160
Bensmind Avatar answered Nov 01 '22 11:11

Bensmind