简体   繁体   中英

How to invoke unit test class in reflection c#

I have a class which is decorated with [TestFixture] attribute and this class contains methods that are decorated with [Test] attribute, each method signature is

public void MethodName([ValueSource("TestConfigurations")] TestConfiguration tConf)

also there are set up and tear down methods

    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
    }

    [SetUp]
    public void TestSetUp() { }

    [TearDown]
    public void TestTearDown()
    {
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
    }

how can I run this unit test class via reflection in c#?

Thank you in advanced

Something like:

public static class RunUnitTestsClass<TUnitTests> where TUnitTests : new()
{
    private static IEnumerable<MethodInfo> WithAttribute<TAttribute>()
    {
        return typeof(TUnitTests).GetMethods().Where(method => method.GetCustomAttributes(typeof(TAttribute), true).Any());
    }

    private static void RunWithAttribute<TAttribute>()
    {
        var unitTests = new TUnitTests();
        foreach (var method in WithAttribute<TAttribute>())
            method.Invoke(unitTests, new object[0]);
    }

    public static void RunTestFixtureSetup()
    {
        RunWithAttribute<TestFixtureSetUp>();
    }

    // same for the rest of them

    public static void RunTests(TestConfiguration tConf)
    {
        var unitTests = new TUnitTests();
        foreach (var method in WithAttribute<Test>())
            method.Invoke(unitTests, new []{tConf});
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM