如何在运行时从NUnit测试运行中获取单元测试方法属性?

时间:2012-08-01 15:33:01

标签: c# reflection attributes nunit

我在一个属性中存储有关给定测试的各种信息(多个bug跟踪系统的ID):

[TestCaseVersion("001","B-8345","X543")]
public void TestSomethingOrOther()

为了在测试过程中获取此信息,我编写了以下代码:

     public string GetTestID()
     {
        StackTrace st = new StackTrace(1);
        StackFrame sf;
        for (int i = 1; i <= st.FrameCount; i++)
        {
            sf = st.GetFrame(i);
            if (null == sf) continue;
            MethodBase method = sf.GetMethod();
            if (method.GetCustomAttributes(typeof(TestAttribute), true).Length == 1)
            {
                if (method.GetCustomAttributes(typeof(TestCaseVersion), true).Length == 1)
                {
                    TestCaseVersion tcv =
                        sf.GetMethod().GetCustomAttributes(typeof(TestCaseVersion), true).OfType<TestCaseVersion>()
                            .First();
                    return tcv.TestID;
                }
            }
        }

问题是当在发布模式下通过NUnit运行测试时,应该具有测试名称和这些属性的方法将替换为以下内容:

System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at NUnit.Core.Reflect.InvokeMethod(MethodInfo method, Object fixture, Object[] args)

更新 对于任何感兴趣的人,我都按照以下方式实现代码(这样可以访问任何属性值,而无需更改任何使用TestCaseVersion属性的现有代码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false)]
public class TestCaseVersion : PropertyAttribute
{
   public TestCaseVersion(string testCaseCode, string story, string task, string description)
   {
      base.Properties.Add("TestId", testCaseCode);
      base.Properties.Add("Description", description);
      base.Properties.Add("StoryId", story);
      base.Properties.Add("TaskId", task);
    }
}

public string GetTestID()
{
   return TestContext.CurrentContext.Test.Properties["TestId"];
}

1 个答案:

答案 0 :(得分:0)

可能我不明白你的想法,但为什么不使用更简单的解决方案?

[TestCase(TestName = "001, B-8345, X543")]
public void TestSomethingOrOther()