JavaDeveloper
JavaDeveloper

Reputation: 5660

How to unit test a private variable?

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.

  1. Should I add an explicit getter only for unit tests?

  2. If not then how to access the value of private unexposed variables ?

Upvotes: 2

Views: 8088

Answers (4)

herman
herman

Reputation: 12305

  1. No.
  2. You don't. You would be coupling your test to your implementation. If you were to refactor your implementation, you would want to have the confidence that if your test keeps working without having to modify it, you didn't break anything.

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

Dawood ibn Kareem
Dawood ibn Kareem

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

dkatzel
dkatzel

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

Edward Ames
Edward Ames

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

Related Questions