views:

159

answers:

3

I am a Java programming now also writing in C#. I have seen Accessor classes generated by the VS test generating software (to give access from Tests to private members or functions). Should I be creating Accessors deliberately and if so why

A: 

If you use accessors, the underlying implementation can be changed without changing the API.

By exposing a public field you expose the internals of how that data is being stored. Using a public property instead allows you more flexibility to change the way the data is stored internally and not break the public interface.

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property's get and set accessors.

Auto-Implemented Properties

Eg:

// Auto-Impl Properties for trivial get and set
public string Name { get; set; }
public int CustomerID { get; set; }
rahul
+2  A: 

The generated accessors in MSTest are there to test the private parts of classes. So already there I would ask myself should we explicitly test internals.

I believe unit tests should only exercise the public face of a class, thus the generated accessor stuff becomes obsolete. In my experience that is a good thing, since I find them non-trivial to maintain especially when things change (as they usually do with refactoring going on).

Peter Lillevold
+1  A: 

In Roy Osherove's The Art of Unit Testing, he mentions a really important thing about consumers of your classes. Unit tests are consumers and use the API. If you need to change the visibility of you api then to test then you should. Don't use accessors if you can avoid it.

In fact I suggest reading this book :-)

Preet Sangha