Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit test to detect a new field/property addition in C#

Suppose I have a class with 3 fields/properties. Assume all my unit tests pass now in my project using this class. If I add a new property to this class(4th field) then I want one unit test to fail. How would I write such a unit test that can detect a property addition?

like image 895
Blue Clouds Avatar asked Sep 13 '25 20:09

Blue Clouds


2 Answers

Here is an example using reflection.

void TheUnitTest()
{
    var p = new Person();
    Assert.That(p.GetType().GetProperties().Count() == 3);
}

public class Person { public String Name{ get; set; } public int age { get; set; } public String job { get; set; } }
like image 152
anthonybell Avatar answered Sep 16 '25 11:09

anthonybell


You don't want to do that. The point of unit testing is to verify functionality, not implementation. You don't add a property on a class just to add it for fun -- you add it as part of implementing some new piece of functionality, and you test that functionality.

If you add a property and it makes no functional difference to your application, then that's fine. You don't need to test it, it's not changing anything about how your codebase functions. You'll test the properties via your tests of functionality.

like image 23
Daniel Mann Avatar answered Sep 16 '25 11:09

Daniel Mann