There is my model class
public class Model
{
public ICollection<string> MyCollection { get; }
}
I want to test MyCollection
getter returns an actual read-only collection. That is clients of the class can neither add nor remove elements to/from it at all. What's the correct way to write such test?
Option 1
Assert.That(modelInstance.MyCollection is IReadonlyCollection<string>);
It's returns true e.g when field of the MyCollection
property 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 find it not elegant since probably there are other ways to modificate a returned collection (such as indexers for List<string>
)
So is changing of type of the property to ReadOnlyCollection<string>
the only solution to achieve needed behavior? At that case I do need any unit tests but it does the type of the MyCollection
more specific.
A collection that is read-only does not allow the addition or removal of elements after the collection is created. Note that read-only in this context does not indicate whether individual elements of the collection can be modified, since the ICollection<T> interface only supports addition and removal operations.
Collection<T>.Contains (T) method is used to determine whether an element is in the Collection< T >. Here, item is the object to locate in the Collection< T >. The value can be null for reference types. Return Value: This method return True if item is found in the Collection< T >, otherwise, False.
For example, the IsReadOnly property of an array that is cast or converted to an ICollection<T> object returns true, even though individual array elements can be modified. Searches the set for a given value and returns the equal value it finds, if any.
According to Microsoft's own documentation from August of 2019 you shouldn't have to do that. If you look under the example section in the document linked below it shows that checking the collection directly IsEmpty (CollectionName) should work, but it doesn't, as I have run into the same issue you did.
ICollection
offers a property called IsReadOnly
that lets you check that your collection instance is read-only without doing any tricks:
Assert.That(modelInstance.MyCollection.IsReadonly);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With