Today I ran into a silly bug. I had to compare 2 strings and I used '==' accidentally. (This can happen a lot when you frequently switch between languages where you can compare strings using the '==' operator).
I didn't pay enough attention because I thought the unit tests are going to detect problems like that. What I didn't know was that java tries to share strings to save memory.
So, non of the unit tests failed (because the strings were shared) and I continued writing code. The long and short of it: some time later I used this method with a dynamically created string (new String("other string")
), which had another id (hash) than String s = 'other string'
.
Is there any way to prevent Java from sharing strings during unit tests. I don't care about the memory usage (during unit tests) since it is more important for the code to work.
I don't want to use new String(...)
every time a unit test uses a string.