Related to yesterday's question. I implemented the solution proposed by Mehrdad Afshari but this caused another problem.
To recap: I have a class containing a dictionary of Type->IList<Type>
e.g. Cat->{cat1, cat2}, Zebra->{zebra1, zebra2}
where Cat
and Zebra
are subclasses of Animal
. Now Mehrdad proposed the following method to retrieve the all animals of a certain type:
IList<T> GetAnimalsOfType<T>() where T : Animal {
return dictionary[typeof(T)].OfType<T>().ToList();
}
This works but breaks my unit test. The reason is that Animal is an abstract class and so I'm using Rhino Mocks to stub it (using animal = MockRepository.GenerateStub<Animal>();
). My unit test for this class tries to create a new animal and then see if it's included in the dictionary.
zoo.AddAnimal(animal);
IList<Animal> animals= zoo.GetAnimalsOfType<Animal>();
Assert.That(animals[0], Is.EqualTo(animal));
Unfortunately the type of animal created by Rhino Mocks is an animal proxy and I'm asking for Animal, which breaks my test. Any suggestions on how to correct the situation?
Update: thanks to all for the solutions.