DEV Community

Discussion on: How to use reflection to test private and protected methods

Collapse
 
nas profile image
Emil

Sometimes there are circumstances that require you to use reflections. Maybe some piece of legacy code that can't be changed right now (because of reasons) but will be changed in the near future.

Generally speaking though;

If you feel like you want to test private/protected methods it is usually a clear indication that the class you are testing "does too much".

Maybe you have some class that internally tokenizes a string. Something like that would be nice to test in isolation but you can't because the method that does the tokenizing is declared as private.

A better way than using reflections to change the accessiblity of the method would be to extract the tokenization code into its own class, a Tokenizer. The main class can now use the tokenizer to tokenize it's strings.

The new Tokenizer class will have public methods and can have it's own unit tests.