0

I have a class Report with properties like Title, Status, Type as shown below:

Public class Report
{
    public string Title { get; set; }
    public string Status { get; set; }
    public string Type { get; set; }
}

All these properties are getting set from values coming from DB. After that, I am passing this object to another API. I am not using get in my own implementation. When I wrote a unit test case and run Code coverage analyzer in Visual Studio 2015, it says that get is not covered. So is it ok to write properties with the only setter in this scenario? Is it the correct way to do? Otherwise, how can I include get in code coverage?

I went through below links but not getting a proper answer as what to do in my case.

Why using only setter in property declaration? Do write-only properties have practical applications?

Vaibhav Dhoke
  • 459
  • 6
  • 14
Ash18
  • 121
  • 3
  • 12
  • I don't understand the question. Does your unit test use the getter? If it does, it should be covered. If it doesn't it should show as not covered in order to remind you to test it. – Charlie Mar 23 '18 at 05:12
  • As I have mentioned I am only setting these properties and passing the object to another API. So my question is whether I should remove get from my properties? Is it ok to have properties with only setter? – Ash18 Mar 23 '18 at 08:53
  • Another possibility is that you could decide that auto implemented properties can be excluded from code coverage. The way of doing this will vary depending on which coverage tool you're using, but from memory, I do it with one of the Attributes which get added to Compiler Generated code. – Richardissimo Apr 03 '18 at 17:37

1 Answers1

0

In terms of the C# language, a setter-only property is legal. However, at least in my view, it does nothing good for code clarity.

The most common use for such a property appears to be when using property-based dependency injection. It looks like that's what you are doing.

If you can use constructor-based injection, I think most folks on your team will find that much clearer. If you can't, or if you prefer the syntax that set's properties on construction, I don't think it does any great harm although some people will see that and try to access the property.

One issue with using the setter for DI is that it can be set multiple times by code using the object. For that reason, I wouldn't do it in an object that is publicly exposed.

Charlie
  • 12,928
  • 1
  • 27
  • 31