This should do the trick.
private static bool hasTestCaseAttribute(MemberInfo m)
{
return m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any();
}
Question
I'm not sure why the below method always returns false
// method to check for presence of TestCaseAttribute
private static bool hasTestCaseAttribute(MemberInfo m)
{
foreach (object att in m.GetCustomAttributes(true))
{
Console.WriteLine(att.ToString());
if (att is TestCase.TestCaseAttribute) // also tried if (att is TestCaseAttribute)
{
return true;
}
}
return false;
}
even though the console output looks like this:
TestCase.DateAttribute
TestCase.AuthorAttribute
TestCase.TestCaseAttribute
What am I missing here?
Edit; this approach seems to work...
private static bool hasTestCaseAttribute(MemberInfo m)
{
if (m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any())
{
return true;
}
else
{
return false;
}
}
Solution
This should do the trick.
private static bool hasTestCaseAttribute(MemberInfo m)
{
return m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any();
}
OTHER TIPS
public static bool HasCustomAttribute(MethodInfo methodInfo, bool inherit = false)
{
return methodInfo.GetCustomAttribute<CustomAttribute>(inherit) != null;
}
You could use the function above which is much more succinct than your current approach. sa_ddam's snippet works too.
You can try this:
private static bool hasTestCaseAttribute(MethodInfo method)
{
object[] customAttributes = Attribute.GetCustomAttribute(method,
typeof(TestCase), true) as TestCase;
if(customAttributes.Length>0 && customAttributes[0]!=null)
{
return true;
}
else
{
return false;
}
}