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 .
source share