Well you have 2 options:
- Use reflection or the MSTest private accessor classes to get and set private field values during your test.
- Just don't worry about it and test the exposed behaviour, even if that means your test depends on other properties or method that are being tested elsewhere.
As you can probably tell from the wording, my choice would be with #2 - You should test the exposed behaviour. In your case the exposed behaviour that you are testing is:
- If I use
AddComponent then the added component should be accessible through the indexer - If I use the indexer, I should be able to access any components that were added through
AddComponent
In this case its fairly obvious that these are pretty much the same thing, so we only really have one unit case / exposed behaviour to test here. Yes this unit test covers two different things, but that shouldn't really matter - we aren't trying to test that each method / property behaves as expected, rather we want to test that each exposed behaviour works as expected.
As an alternative, suppose that we go for option 1 and used private reflection to check the state of _components ourselves. In this case the bevahour that we are actually testing is:
- If I use
AddComponent then the added component should be added to _components - If I use the indexer, I should be able to access any components that are in
_components
Not only are we now testing the internal behaviour of the class (so that if the implementation changes the tests fail, even if the class is working as expected), but we have just doubled the number of tests we are writing.
On top of that, by increasing the complexity of our tests we are increasing the chance that the tests themselves have a bug - for example what if we made a mistake and in test 2. we checked some completely different private field? In this case not only have we made more work for ourselves, but we aren't even testing the actual behaviour that we want to test!