Testing private variables is always bad practice?

To give some experience, I’ve been learning Java for about 10 months now, so I really don’t worry so much. I recently read about how its bad practice to test private methods and variables.

In an ideal world, you should not do this because it speaks of poor design, however I work with an outdated structure where most methods are invoked through reflection, and this is poor design, but I can’t change it no matter what. Please do not respond by saying “you must reverse engineer your code”, as I cannot change the way the framework works.

I want to verify that the "flow" class behaves in a certain way and calls the correct methods depending on the state of private variables, and I want certain methods to set private instance variables to the correct value if another private variable has a specific value. This happens when I make future changes to the class, I can guarantee that the thread / behavior of the class has not broken or changed.

Now, since the stream is mainly based on the state of private instance variables and because it is bad to check the state of private instance variables - how else can I check the class?

Ways to test private variables that all work:

  • Deploy the default recipients and setters at the end of the code and put the junit test class in the same package. Comment it clearly that they should be used only for testing.

  • Make default variables default instead of private and put the junit testing class in the same package. No other classes in the same package will instantiate this class.

  • Test private variables by reflection - I lose the IDE's functionality here, because Eclipse will not refactor if I change the name of the variables and it will be a future pain to manually change the lines to match the variable names in the testing class.

Which of the three above is the "lesser" evil to use? Is it better to test private variables and then no tests at all?

+4
2

. .

, , .

, , , , .

, 1000 , - , .

, .

+7

. , , - , , .

0

Source: https://habr.com/ru/post/1534035/


All Articles