Posts

Showing posts from August, 2016

Unit Testing a Singleton Using PowerMock

I came across an interesting problem this week at work. I had to make some changes to a Singleton class in Java, and had some issues when trying to unit test the changes. When JUnit runs each test method with the @Test annotation, a new object of the test class is instantiated, this ensures that there are no side effects between test cases. However, the Singleton class that is under test returns a reference to it's object upon each invocation of it static factory method. This can be a problem for your test cases because they are referencing the same object under test, opposed to a new one, which can cause side effects from previous tests. Luckily you can get around this issue using PowerMock. The code snippets below show how to do this yourself... Code Example SingletonTest.java 1| package test; 2| 3| import static org.junit.Assert.fail; 4| import main.Singleton; 5| 6| import org.junit.Before; 7| import org.junit.Test; 8| import org.junit.runn