Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jindeveloper/51deadcb3aef471dfab2da49a528b9a6 to your computer and use it in GitHub Desktop.

Select an option

Save jindeveloper/51deadcb3aef471dfab2da49a528b9a6 to your computer and use it in GitHub Desktop.
[Fact]
public void Test_Read_Attributes()
{
//get the Product-class
var type = typeof(Product);
//Get the attributes of the Product-class and we are expecting the [Serializable]
var attribute = (SerializableAttribute)type.
GetCustomAttributes(typeof(SerializableAttribute), false).FirstOrDefault();
Assert.NotNull(attribute);
//Check if [Serializable] has been read.
//Let's check if the type of the attribute is as expected
Assert.IsType<SerializableAttribute>(attribute);
//Let's get only those 2 methods that we have declared
//and ignore the special names (these are the auto-generated setter/getter)
var methods = type.GetMethods(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.DeclaredOnly)
.Where(method => !method.IsSpecialName).ToArray();
//Check if the product-class has two methods
//Let's check if the Product-class has two methods.
Assert.True(methods.Length == 2);
Assert.True(methods[0].Name == "GetProductFullName");
Assert.True(methods[1].Name == "RunOnlyOnDebugMode");
//Check if each methods does have attributes.
Assert.True(methods.All( method =>method.GetCustomAttributes(false).Length ==1));
//Let's get the first method and its attribute.
var obsoleteAttribute = methods[0].GetCustomAttribute<ObsoleteAttribute>();
// Check if the method GetProudctFullName is using the Obsolete attributes.
Assert.IsType<ObsoleteAttribute>(obsoleteAttribute);
//Let's get the second method and its attribute.
var conditionalAttribute = methods[1].GetCustomAttribute<ConditionalAttribute>();
//Check if the method RunOnlyOnDebugMode is using the Conditional attributes.
Assert.IsType<ConditionalAttribute>(conditionalAttribute);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment