The right way to check if ICollection is really read-only

There is my model class

public class Model { public ICollection<string> MyCollection { get; } } 

I want to check MyCollection getter returns the actual read-only collection. That is, class clients can neither add nor delete elements to / from it at all. What is the right way to write such a test?

Option 1

 Assert.That(modelInstance.MyCollection is IReadonlyCollection<string>); 

It returns true, for example, when the MyCollection property MyCollection is an instance of List<string> (it implements IReadonlyCollection<string> ).

Option 2

 var testDelegate = () => modelInstance.MyCollection.Add("QWERTY"); Assert.That(testDelegate, Throws.TypeOf<NotSupportedException>()); 

I believe this is not elegant, as there may be other ways to modify the returned collection (e.g. indexers for List<string> )

So, is changing the property type to ReadOnlyCollection<string> only solution to achieve the required behavior? In this case, I need some unit tests, but this is a more specific type of MyCollection .

+5
source share
2 answers

ICollection offers the IsReadOnly property, which allows you to verify that your collection instance is read-only, without any tricks:

 Assert.That(modelInstance.MyCollection.IsReadonly); 
+10
source

dasblinkenlight answered your question directly: use IsReadOnly . Your other question is good too:

So, is changing the property type to ReadOnlyCollection<string> only solution to achieve the required behavior?

This is not the only solution, but I think it is the best.

You must declare your property as IReadOnlyCollection<string> if it is a collection. The API of your classes or interfaces should describe how they should be used, and let me know (as a consumer of your code) how to expect behavior from them.

For example, it has a bad code smell that has the IList<string> property, but throws an exception when elements are added or removed. If you are modeling a read-only collection, be clear and use IReadOnlyCollection<string> if you can.

Your example is a bit more subtle, but when you see things like checking if an interface method will throw a NotSupportedException , this is good advice to make sure the interface correctly describes the behavior of your class.

0
source

Source: https://habr.com/ru/post/1276231/


All Articles