You can use PowerMock to inject your test ObjectMapper instance using ConstructorMocking.
http://benkiefer.com/blog/2013/04/23/powermockito-constructor-mocking/
I had to modify your example singleton so that the constructors were chained correctly.
public class MySingleton {
ObjectMapper mapper;
private MySingleton()
{
//This does not work.
//new MySingleton(new ObjectMapper());
this(new ObjectMapper());
}
private MySingleton(ObjectMapper mapper)
{
this.mapper = mapper;
}
private static final class Lazy
{
static final MySingleton INSTANCE = new MySingleton();
}
public static MySingleton getInstance()
{
return Lazy.INSTANCE;
}
}
I also stubbed the ObjectMapper Class.
public class ObjectMapper {
//Empty Sample uses default CTR
}
I was able to test this as follows using the instructions from the link previously listed:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(MySingleton.class)
public class MySingletonTest {
@Test
public void testSingletonCtr() throws Exception {
ObjectMapper mapper = new ObjectMapper();
PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);
Assert.assertEquals(MySingleton.getInstance().mapper, mapper);
}
}
I am doing this in a maven project. I needed the following dependencies added to my test scope:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
I do tend to agree that Singletons tend to cause problems long-term for code maintenance and scalability. If you have capacity to look for alternative approaches to your problem it may benefit you to do so. If not, then I believe that the PowerMock utility will provide you the capability you're looking for.
Best of Luck.