2

I am writing unit tests (using JUnit and Mockito) for a singleton Java class. I cannot change the class implementation itself.

With PowerMockito, it was like this (and works):

@Mock
    private TheSingleton theSingleton;

@Before
    public final void setUp()
        throws Exception
    {
        MockitoAnnotations.initMocks( this );

        PowerMockito.mockStatic( TheSingleton.class );
        when( TheSingleton.getInstance() ).thenReturn( theSingleton );
        ...
    }

The ask is to rewrite the test without using PowerMock or PowerMockito or any other static mocking API. Since I cannot change the singleton class to instead use dependency injection, I am not sure what would be a good way of doing this.

Any help will be greatly appreciated.

techjourneyman
  • 1,701
  • 3
  • 33
  • 53

2 Answers2

0

You essentially don't have other options. Without any sort of static mocking framework, such as PowerMock or PowerMockito or writing your own code that does the same sort of thing that these do, you won't be able to do what you want. Sorry, I know that's not the answer you want, but I do believe it is the answer.

See also How to change method behaviour through reflection? and Why does Mockito not mock static methods? for more insight.

Shawn
  • 8,374
  • 5
  • 37
  • 60
0

durian-globals is a reflection-free way to achieve this. You do sacrifice a tiny bit of runtime performance, but it hasn't been a measurable amount in any of our production use-cases.

Ned Twigg
  • 2,159
  • 2
  • 22
  • 38