Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of checking if a ICollection is actually read-only

Tags:

c#

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.

like image 364
Ilya Loskutov Avatar asked Apr 03 '18 15:04

Ilya Loskutov


People also ask

What does it mean when a collection is read only?

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.

How to check if an element is in the collection<T>?

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.

How does isreadonly work in icollection?

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.

Do I have to check if a collection is empty?

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.


1 Answers

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);
like image 101
Sergey Kalinichenko Avatar answered Oct 02 '22 17:10

Sergey Kalinichenko