Greetings fellow Coderanchers,
I have some questions regarding
unit testing singletons and/or "static" classes [in
java] and what are the potential alternatives. I'm aware this is a loaded question so I'll try my best to funnel to my issue.
I'm currently creating a simple wrapper around some of the java.nio libraries so I can use them in my application. Here's the code for reference:
http://hastebin.com/tadeyicuho.java (sorry for the link, the code is class is 103 lines).
One of the goals when I was writing this is that I wanted to get 100% coverage so as I wrote this class I also wrote unit tests until I hit a bump in the road here:
At this point I turned to mocking using
Mockito and PowerMock so I could handle final classes as well as mocking static methods. Unfortunately, PowerMock is not intuitive and I kept getting an unresolvable error that seemed to have even stumped StackOverflow. Anyway, so I turned to a singleton:
http://hastebin.com/xipisibuze.java
I updated all my unit tests to reflection this change and my code coverage dropped from 85% coverage to 8%. At this point I found these articles:
http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/http://programmers.stackexchange.com/questions/40373/so-singletons-are-bad-then-whatMultiple threads on this forum saying Singletons are less than ideal
In my reading I found
guice so I could essentially simulate singletons (I think, at least), but I'm wondering if this:
AppropriateIs there a better, more test-friendly solution/design pattern
At the end of the day, I just want to learn what I should do in situations like this in the future. What can be done? How does one go about unit testing file I/O operations? What about testing static classes? Singletons?