How to traverse class properties for Nunit tests?
-
Hi I am working on a project in which I need to NUnit testing. To do that I need to write tests for each class. I am trying to automate that process. 1. How to know names of public properties of class in .Net dynamically? 2. I am also looking for property types to set some default values. 3. There might be nested classes also. I am wondering how to traverse that nested tree? Please advice. Thanks Pankaj
-
Hi I am working on a project in which I need to NUnit testing. To do that I need to write tests for each class. I am trying to automate that process. 1. How to know names of public properties of class in .Net dynamically? 2. I am also looking for property types to set some default values. 3. There might be nested classes also. I am wondering how to traverse that nested tree? Please advice. Thanks Pankaj
-
Hi I am working on a project in which I need to NUnit testing. To do that I need to write tests for each class. I am trying to automate that process. 1. How to know names of public properties of class in .Net dynamically? 2. I am also looking for property types to set some default values. 3. There might be nested classes also. I am wondering how to traverse that nested tree? Please advice. Thanks Pankaj
I'm sure if you look around you'll find something that already exists to do this kind of job.
-
Hi I am working on a project in which I need to NUnit testing. To do that I need to write tests for each class. I am trying to automate that process. 1. How to know names of public properties of class in .Net dynamically? 2. I am also looking for property types to set some default values. 3. There might be nested classes also. I am wondering how to traverse that nested tree? Please advice. Thanks Pankaj
Using LINQ because it's so much easier... :cool: 1) How to know names of public properties of classes in .NET dynamically?
var properties = yourType.GetProperties().Select(p => p.Name); // Returns an IEnumerable<string> of the names (only returns public by default)
- Property types
var properties = yourType.GetProperties().Select(p => p.PropertyType); // Returns IEnumerable<Type> of property type
var instance = Activator.CreateInstance(properties.First()); // Creates the default value for the type of the first property in list- Nested classes
var childClasses = typeof(Program).GetNestedTypes().Select(t => t.Name); // Returns IEnumerable<string> of names of child properties
Note you can retrieve these without LINQ just forget the
.Select(...)
pattern, but you asked for names which implies strings so I used LINQ to extract the names rather than a loop.