11

我将特定测试方法的测试数据保存在与函数名称相同的文件夹中。我以前在每个 中都有相同的函数调用[TestMethod]ClearAllAndLoadTestMethodData()它通过 确定方法名称StackTrace。现在,我将此功能移至[TestInitialize]. 如何找到即将执行的方法的名称?

我想TestContext提供这个。我可以通过它访问它,[AssemblyInitialize()]并且在第一次运行时,它的属性Name设置为测试方法的名称。但是,稍后这不会改变(如果我将对象保存在静态字段中)。

4

2 回答 2

24

AssemblyInitialize方法在所有测试之前只执行一次。

使用TestContext里面的TestInitialize方法:

[TestClass]
public class TestClass
{
    [TestInitialize]
    public void TestIntialize()
    {
        string testMethodName = TestContext.TestName;
    }

    [TestMethod]
    public void TestMethod()
    {
    }

    public TestContext TestContext { get; set; }
}
于 2012-08-30T13:43:45.480 回答
0
[TestClass]
public class MyTestClass
{
    private static TestContext _testContext;

    [ClassInitialize]
    public static void TestFixtureSetup(TestContext context)
    {
        _testContext = context;
    }

    [TestInitialize]
    public void TestIntialize()
    {
        string testMethodName = MyTestClass._testContext.TestName;
        switch (testMethodName)
        {
            case "TestMethodA":

                //todo..

                break;
            case "TestMethodB":

                //todo..

                break;              
            default:
                break;
        }
    }

    [TestMethod]
    public void TestMethodA()
    {
    }

    [TestMethod]
    public void TestMethodB()
    {
    }   
}
于 2019-10-27T21:12:15.833 回答