[英]Get value of custom attribute without providing class name and/or method name
我知道我在重复这个问题,我已经经历了一些类似的解决方案,但是我正在寻找一个不同的解决方案。
我想读取自定义定义属性的值。 我下面有一段代码可以帮我实现,但是我不想硬编码类名和/或方法名,因为那样对我没有用。 我想使此方法可重用,以便可以从所有可用的测试方法中读取值。
[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中实现吗? 如果是,请协助我解决。
您可以使用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
}
这将获取参数的值。
您可以使用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();
}
您可以在文档中获取有关StackFrame的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.