I am working on a lib that I want to release in open source. I have started writing the tests for the code, and I was wondering how I am suppose to test a property in a .Net object. Lets say I have the following:
public class Person{ #region variables private string _name = String.Empty; private string _surname = String.Empty; #region properties public string Name{ get{ return _name; } } public string Surname{ get{ return _surname; } set{ _surname = value; } } }
I have two questions related to the code:
- How do I Unit test a Property that just has a getter (Like Name in the example)
- How do I Unit test a Property with a setter and a getter (Like Surname in the example)
I want to test properties that are that simple because I have already found errors in other code were Itellinsense did the wrong autocomplete and the property was not returning the correct variable.
Update:
I am not talking about simple properties as the one in the example, they do have some logic behind them and are quite hard to debug. Writing a test that uses the setter to test the getter and vice versa is not good because if there is a fail I won’t know which method to blame. I am using properties because they were added as public variables and later more logic had to be added.
Really not so different from testing if you had a setter. you’ll just need to find another way of determining the output. Could be in a ctor, or the result of other setters/operations on the object.
If we had setters for Name and SurName, but only a getter for FullName, the test could look like this: