Reputation: 5660
Consider a linkedlist class and I maintain 2 private variables 1. firstNode and 2. lastNode. These variables are only for internal use thus, not exposed via getters. I want to test that operations do modify these 2 variables as expected. Eg: eliminating duplicate in sorted linkedlist should change the last node if last node was a duplicate.
Should I add an explicit getter only for unit tests?
If not then how to access the value of private unexposed variables ?
Upvotes: 2
Views: 8088
Reputation: 12305
Think about what will go wrong (i.e. which part of the contract will be violated) if those variables are not correctly updated. Write a test for that, prove that it fails when it should, then make sure it doesn't fail.
Upvotes: 2
Reputation: 79828
Don't do it. You should be testing the behaviour of your linked list, not its implementation. Work out how your linked list should behave in various circumstances, and derive test cases from its expected behaviour. If you find yourself writing a test case that needs to look into the implementation of a class (including its private members), then your test is not actually ensuring the correctness of the class's behaviour.
Upvotes: 3
Reputation: 31648
You shouldn't test private variables, only things that are public. Testing private data is testing implementation details which are very fragile. If you were to ever change your implementation, those tests would fail or no longer compile.
Instead, write tests that only test the public API. In your example of using a linked list, your tests should modify the list and then walk over the structure using the public methods to go from node to node to make sure all the nodes are correct.
Upvotes: 3
Reputation: 129
You could try to make it package-level getters. The get functions won't be exposed but you can still check.
Upvotes: 0