JUnit recipes: Work around static attributes in classes

Beware of the class loader. I recently had a major testing problem with some code because I didn’t take the (sometimes ugly) Java class loading mechanism into account. There was a small class where I wanted to unit test the calculateAge method.

So I dropped EasyMock into my project and mocked the person class. I was using jMock in the past and could live with methods as strings. With the new JMock 2 syntax this has changed. I still struggle with {{ in JMock expectations and so does my IDE. When IDEA learns to format JMock expectations, I’m back. For now I’m using EasyMock though, sometimes with JMock assertions from the excellent Hamcrest assertion library. Back to the problem at hand . The mock was passed into the AgeCalculator to calculate the age of the person. The problem was the Person class.

Even though I didn’t use the Person class, just a mock, the static attributes where initialized and the DatabaseConfiguration tried to load data from the backend. This happens whenever your classloader sees the Person type, even in an interface.

Using Calculator in mocks will initialize the static attributes in Person. Which contradicted the isolation principle of unit tests and also led to long startups of the database backend. This stopped my efforts to test the AgeCalculator. Time passed.

Then I stumbled upon JMockit. Others have too. The friendly and supportive developers of JMockit have helped (thanks Rogerio) and with a simple line I was saved:

Constructs like the above with static attributes should never be created in the first place (hello all those people who propagate static inialized attributes for singletons to avoid synchronized). But if you have such code in your legay base, JMockit to the rescue.

Thanks for listening.

120 thoughts on “JUnit recipes: Work around static attributes in classes”

  1. Pingback: buy cs go
  2. Pingback: ????? ????
  3. Pingback: de nature jakarta
  4. Pingback: obat kutil kelamin
  5. Pingback: obat kencing nanah
  6. Pingback: Jual Obat Sipilis
  7. Pingback: itu
  8. Pingback: keluar
  9. Pingback: para para dinle
  10. Pingback: economics tuition
  11. Pingback: lendir
  12. Pingback: Obat Kencing Panas
  13. Pingback: obat
  14. Pingback: denature
  15. Pingback: obat herbal
  16. Pingback: My Drone View
  17. Pingback: Obat Kencing Nanah
  18. Pingback: Gonore Pada Pria
  19. Pingback: Kutil di Anus
  20. Pingback: Obat Untuk Gonore
  21. Pingback: Obat Herbal Eksim
  22. Pingback: Obat Eksim
  23. Pingback: Obat Kutil Kelamin
  24. Pingback: nanah
  25. Pingback: kelamin
  26. Pingback: Obat Sipilis Alami

Comments are closed.