How to TDD test that objects are being added to a collection if the collection is private?
Posted
by
Joshua Harris
on Programmers
See other posts from Programmers
or by Joshua Harris
Published on 2012-11-16T21:19:33Z
Indexed on
2012/11/16
23:16 UTC
Read the original article
Hit count: 364
Assume that I planned to write a class that worked something like this:
public class GameCharacter {
private Collection<CharacterEffect> _collection;
public void Add(CharacterEffect e) { ... }
public void Remove(CharacterEffect e) { ... }
public void Contains(CharacterEffect e) { ... }
}
When added an effect does something to the character and is then added to the _collection. When it is removed the effect reverts the change to the character and is removed from the _collection.
It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?
What test could I write to start constructing this class. I could write a test where Contains would return true for a certain effect being in _collection, but I can't arrange a case where that function would return true because I haven't implemented the Add method that is needed to place things in _collection.
Ok, so since Contains is dependent on having Add working, then why don't I try to create Add first. Well for my first test I need to try and figure out if the effect was added to the _collection. How would I do that? The only way to see if an effect is in _collection is with the Contains function.
The only way that I could think to test this would be to use a FakeCollection that Mocks the Add, Remove, and Contains of a real collection, but I don't want _collection being affected by outside sources. I don't want to add a setEffects(Collection effects) function, because I do not want the class to have that functionality. The one thing that I am thinking could work is this:
public class GameCharacter<C extends Collection> {
private Collection<CharacterEffect> _collection;
public GameCharacter() {
_collection = new C<CharacterEffect>();
}
}
But, that is just silly making me declare what some private data structures type is on every declaration of the character.
Is there a way for me to test this without breaking TDD principles while still allowing me to keep my collection private?
© Programmers or respective owner