0

Is there a way to write unit test that prove class has only public members?

I've done some research about the problem and tried some code but I don't have a solution so far. I am stuck at the point where i need to check are there any private property.

//In the unit test
var viewModels = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes())
                .Where(a => a.Namespace != null && 
                 a.Namespace.StartsWith("Test.Solution"))
                .Where(t => t.Name.EndsWith("View"))
                .ToList();

//ViewModels
 public class PersonView {
   public string DurationMinutes; // don't take this into consideration

   public string Name { get; set; } 
   public string LastName { get; set; } 
   private string Number{ get; set; } 

 // take into consideration only properies with getter and setter
}
PeterZ
  • 137
  • 2
  • 13
  • 1
    `DurationMinutes` isn't a property; it's a field. – Kenneth K. Aug 14 '19 at 16:00
  • Possible duplicate of [Getting non-public properties of a type via reflection](https://stackoverflow.com/questions/3767417/getting-non-public-properties-of-a-type-via-reflection) – gunr2171 Aug 14 '19 at 19:20

2 Answers2

4

For a type, T you can get the number of non-public properties using reflection:

var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var numberOfNonPublicProperties = typeof(T).GetProperties(flags).Length;
Sean
  • 60,939
  • 11
  • 97
  • 136
1

Use Reflection. Basically, .GetType().GetProperties() (if I remember correctly) with appropriate flags. In case you're interested not only in properties, but as well fields, you have to include them also. And then just check that resulting list is empty. LINQ will be handy here.

Zazaeil
  • 3,900
  • 2
  • 14
  • 31