获取自定义属性的值而不提供类名和/或方法名

问题描述 投票:1回答:2

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

我想读取自定义属性的值。我有以下代码为我做的,但我不想硬编码类名和/或方法名,因为它对我没用。我想使这个方法可重用,以便它可以用于从所有可用的测试方法中读取值。

属性定义:

[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实现这个目标吗?如果是的话,请帮我解决。

c# selenium selenium-webdriver nunit custom-attributes
2个回答
2
投票

您可以使用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
    }

这将获得参数的值..


0
投票

您可以使用StackFrame获取对调用方法的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中获得有关StackFrame的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.