如何在反射c#中调用单元测试类

时间:2016-03-15 09:52:03

标签: c# unit-testing reflection nunit

我有一个用[TestFixture]属性修饰的类,这个类包含用[Test]属性修饰的方法,每个方法签名都是

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

还有设置和拆除方法

    [TestFixtureSetUp]
    public void TestFixtureSetUp()
    {
    }

    [SetUp]
    public void TestSetUp() { }

    [TearDown]
    public void TestTearDown()
    {
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
    }

如何通过c#中的反射运行此单元测试类?

先谢谢你

1 个答案:

答案 0 :(得分:0)

类似的东西:

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});
    }
}