代码之家  ›  专栏  ›  技术社区  ›  Appu Mistri

在不提供类名和/或方法名的情况下获取自定义属性的值

  •  1
  • Appu Mistri  · 技术社区  · 8 年前

    我知道我在重复这个问题,我已经经历了一些类似的解决方案,但我正在寻找一个不同的解决方案。

    我想读取自定义属性的值。我下面有一段代码可以帮我完成这项工作,但我不想硬编码类名和/或方法名,因为这样对我来说就没用了。我想让这个方法可重用,以便它可以用来读取所有可用测试方法的值。

    属性定义:

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class TestDataFile : Attribute
    {
        public string Path { get; set; }
        public string Name { get; set; }
    }
    

    访问属性:

    var attribute = (TestDataFile)typeof(DummyTest).GetMethod("Name").GetCustomAttributes(typeof(TestDataFile), false).First();
    

    用法:

    [TestFixture]
    public class DummyTest
    {
        [Test]        
        [TestDataFile(Name="filename.json")]
        [TestCaseSource("LoadTestData")]
        public void AlwaysTrue(Dictionary<string, string> testCaseData)
        {
            // use test data here
        }
    }
    

    我们能在c-sharp中实现这一点吗?如果是,请帮助我解决问题。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Sathish    8 年前

    您可以使用 TestCaseSource测试用例源 而不是创建新的自定义属性并从中检索值。请查找示例代码段以使用带参数的TestCaseSource

    [TestCaseSource("PrepareTestCases", new object[] { "filename.json" })]
    

    请添加源名称为的静态方法

    protected static object[] PrepareTestCases(string param)
        {
            Console.WriteLine(param);
            return new object[] { }; // do return the object you need
        }
    

    这将获得参数值。。

        2
  •  1
  •   taquion    8 年前

    您可以使用 调用栈 获取调用方法的MethodBase引用。考虑以下示例:

    class Foo
    {
        [TestDataFile(Name = "lol")]
        public void SomeMethod()
        {
            var attribute = Helper.GetAttribute();
            Console.WriteLine(attribute.Name);
        }
    
        [TestDataFile(Name = "XD")]
        public void SomeOtherMethod()
        {
            var attribute = Helper.GetAttribute();
            Console.WriteLine(attribute.Name);
        }
    }
    

    还有我们的助手方法,魔法实际发生的地方:

    public static TestDataFile GetAttribute()
    {
        var callingMethod = new StackFrame(1).GetMethod();
        var attribute = (TestDataFile)callingMethod.GetCustomAttributes(typeof(TestDataFile), false).FirstOrDefault();
        return attribute;
    }
    

    测试:

    private static void Main()
    {
        var foo = new Foo();
        foo.SomeMethod();
        foo.SomeOtherMethod();
        Console.ReadLine();
    }
    

    您可以在 documentation