Problem :
I have a collection of entities in my repository. Those entities are not supposed to be visible to the outside world. But, In a test I am supposed to see if all objects are still there and I can’t use the GetAll method because it goes to the database and return everything, not just the collection of entities in my repository.
Solution :
I could expose the collection but how can I be sure that nothing will be changed. I could create a copy of the collection but that would not reflect the “Entity” concept. I know that Java has support for returning a read-only collection. A little bit of search and I found the class ReadOnlyCollection<T>. This is thread-safe and any changes to the original collection will be reflected in it since it is only a wrapper.
public static IList<IRecipe> _identityMap = new List<IRecipe>(); public IList<IRecipe> IdentityMap { get { return new ReadOnlyCollection<IRecipe>(_identityMap); } }
Could not be easier!