Why does Diffblue not use reflection?

You used to support reflection to test private methods; why have you stopped? Someone said reflection was bad practice but I can’t get a good answer why?

Any ideas?

Using Reflection in unit tests has a couple of problems:

  1. Tests using Reflection can be quite fragile - the unit test ends up testing not just the behaviour of the code under test, but also to a large extent the precise naming/structure of elements of the code. This can often mean that fairly trivial changes made by a programmer, such as renaming a private field, can cause failures in your unit tests.
  2. It changes the nature of unit tests from being a test of the externally visible behaviour of your class/methods, into a ‘white box’ test of the exact implementation details. This is often considered to be against Test Driven Development goals, for instance.
  3. Tests using reflection are often hard to read and understand :slight_smile: Which means that when they fail, they are often harder to fix.

Of course, sometimes people really do want to test a private method in isolation and they resort to using reflection. However, its often possible to reconsider the architecture of such a class or method to make it easier to test without reflection.

3 Likes