You have 2 options:
- Use reflection or private access classes of the MSTest class to get and set private field values โโduring the test.
- Just donโt worry about it and do not test the exposed behavior, even if it means that your test depends on other properties or a method that are tested elsewhere.
As you can probably tell from the wording, my choice would be with No. 2 - you have to check the behavior . In your case, the testable behavior you are testing is:
- If I use
AddComponent , then the added component should be accessible using an indexer - If I use an indexer, I must have access to any components that have been added through
AddComponent
In this case, it is pretty obvious that this is almost the same thing, so we really only have one case with the case / exposed behavior for testing here. Yes, this unit test covers two different things, but it does not really matter - we are not trying to verify that each method / property behaves as expected, rather we want to verify that each open behavior works as expected.
Alternatively, suppose we go for option 1 and used personal reflection to check the state of the _components themselves. In this case, the bevahour we are actually testing is:
- If I use
AddComponent , the added component should be added in _components - If I use an index, I must have access to any components found in
_components
We not only test the internal behavior of the class (so if the implementation changes, the tests fail even if the class works as expected), but we just doubled the number of tests we write.
In addition, increasing the complexity of our tests, we increase the likelihood that the tests themselves have a mistake - for example, what if we made a mistake in test 2. did we check several completely different private fields? In this case, we not only did more work for ourselves, but we donโt even check the actual behavior that we want to check!
Justin
source share