Reputation: 649
I have a read-only property on a class that I am testing.
public string ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
Is there a way to write an NUnit test that ensures that this property is readonly? Does the fact that I want to do this at all cause you to raise your eyebrow? It seems to me that adding tests to ensure that read-only properties remain read-only unless a deliberate decision is made to change them is just as important as any other behavior.
Thanks in advance for the feedback.
Upvotes: 1
Views: 2120
Reputation: 84765
It seems to me that adding tests to ensure that read-only properties remain read-only unless a deliberate decision is made to change them is just as important as any other behavior.
I agree, but I dare say that unit testing is the wrong way. Here's why:
Unit testing is generally used to test the dynamic aspects of code, i.e. its run-time behaviour. You, on the other hand, are looking for a way to test a static (compile-time or design-time) aspect of your code. It would seem to me that tools such as FxCop or NDepend are more appropriate in this case. (I may be wrong about these particular tools being appropriate since I don't know them very well myself.)
That being said, as you've already learned from previous answers, you could do this using reflection:
typeof(SomeType).GetProperty("ReadOnlyProperty").CanWrite == false
Upvotes: 7
Reputation: 333
You should be able to use reflection (specifically PropertyInfo.GetSetMethod, which will return null if there is no set accessor defined).
Upvotes: 3