3

I have been through this question on SO regarding unit testing private methods and fields and this answer says that it can be done via reflection mechanism . But there is a commnent saying that it would fail miserably in case of obfuscation .Why is it so ?

Community
  • 1
  • 1
Geek
  • 26,489
  • 43
  • 149
  • 227

2 Answers2

6

Obfuscation works by replacing symbol names (method, field ..) with difficult to read names. So after de-compiling you get a java files, you get a really useless java code.

The method name would have changed, so finding via reflection will not work. (unless the test code uses reflection with obfuscated method name- not an easy job )

Jayan
  • 18,003
  • 15
  • 89
  • 143
  • "So after de-compiling you get a java files, you get a really useless java code." Can you explain this a little bit more . When the code gets compiled , do we compile the obfuscated code or the unobfuscated code ? – Geek Sep 06 '12 at 09:45
  • @Geek - he means that the original method names have been replaced with names like "a", "b", "c" and so on ... which is "really useless" if you are trying to read the code. – Stephen C Sep 06 '12 at 09:48
  • @StephenC but whatever names are given by the obfuscator we still know the names right ? – Geek Sep 06 '12 at 09:50
  • 1
    Not necessarily. Make a small change to the code, rerun the obfuscator and the obfuscated names can all be different. Besides, do **you** want to go through a large number of unit test classes mapping (by hand!) the original method name strings to their obfuscated equivalents? And do **you** want to maintain 2 sets of unit tests, one with the original names and the other with the obfuscated names? – Stephen C Sep 06 '12 at 09:56
4

Obfuscation can rename private methods to whatever it likes (it can't do it with public methods because other packages may depend on it).

The danger of reflection is that you have a string representing a method name; the obfuscater can't detect that this string refers to a private method, so it's free to rename the method as it sees fit.

Jeff Foster
  • 43,770
  • 11
  • 86
  • 103
  • when the code gets compiled , it gets compiled after obfuscation right ? So we know which is the private method name based on private modifier . What am I missing here ? – Geek Sep 06 '12 at 09:49
  • No, most obfuscation software operates on compiled byte code. The code is compiled and then the internal symbols are renamed (and more) by the obfuscator. – Jeff Foster Sep 06 '12 at 10:04