How to get the unit test method name at runtime from within the unit test?

后端 未结 5 1692
栀梦
栀梦 2020-12-28 14:57

How to get the unit test name from the within unit test?

I have the below method inside a BaseTestFixture Class:

public string GetCallerMethodName()
         


        
5条回答
  •  醉梦人生
    2020-12-28 15:10

    If you are not using Nunit or any other third party tool. you will not get TestAttribute.

    So you can do this to get Test Method name. Use TestMethodAttribute insted of TestAttribute.

        public string GetTestMethodName()
        {
                // for when it runs via Visual Studio locally
                var stackTrace = new StackTrace();
                foreach (var stackFrame in stackTrace.GetFrames())
                {
                    MethodBase methodBase = stackFrame.GetMethod();
                    Object[] attributes = methodBase.GetCustomAttributes(typeof(TestMethodAttribute), false);
                    if (attributes.Length >= 1)
                    {
                        return methodBase.Name;
                    }
                }
                return "Not called from a test method";
        }
    

提交回复
热议问题