Search code examples
javaunit-testingmockingpowermockeasymock

Singleton class not getting mocked


I have a singleton class SvnPlugin whose getInstance() i need to mock to return a mock object. But it's not getting mocked. I am using Powermock and Easymock.

Following is my test code

@Test
@PrepareForTest({SVNPlugin.class})
public void createGlobalUSerTest() throws Exception{
    PowerMock.mockStatic(SVNPlugin.class);
    SVNPlugin svnPlugin=PowerMock.createMock(SVNPlugin.class);
    PowerMock.expectNew(SVNPlugin.class).andReturn(svnPlugin);      

    EasyMock.expect(SVNPlugin.getInstance()).andReturn(svnPlugin).anyTimes();
    EasyMock.expect(svnPlugin.getSynProject("", "", "", "")).andReturn(true);
    PowerMock.replay(SVNPlugin.class,svnPlugin);
    Future<RpcResult<CreateGlobalUserOutput>> 
       result=impl.createGlobalUser(getGLobalUser());
    PowerMock.verify(svnPlugin,SVNPlugin.class);
    Assert.assertNotNull(result);       
}

The sample code which it needs to mock is

SVNPlugin svnplugin = SVNPlugin.getInstance();
checkOutFlg = svnplugin.getSynProject(checkOutLocationAtLocal, svnPath , userName, passWord);

I am unable to understand what I am doing wrong.


Solution

  • The quick answer is that you need the Powermock runner.

    Then, in fact you don't need to mock new since mocking getInstance is enough.

    I assumed that SVNPlugin is final, which justify the mock created with Powermock. So I tried with this implementation.

    public final class SVNPlugin {
      public static SVNPlugin getInstance() {
        return new SVNPlugin();
      }
    
      private SVNPlugin() {}
    
      public boolean getSynProject(String s, String s1, String s2, String s3) {
        return false;
      }
    }
    

    And the following test is working perfectly.

    @RunWith(PowerMockRunner.class)
    public class SVNPluginTest {
    
      @Test
      @PrepareForTest(SVNPlugin.class)
      public void createGlobalUSerTest() throws Exception{
        PowerMock.mockStatic(SVNPlugin.class);
        SVNPlugin svnPlugin = PowerMock.createMock(SVNPlugin.class);
    
        EasyMock.expect(SVNPlugin.getInstance()).andStubReturn(svnPlugin);
        EasyMock.expect(svnPlugin.getSynProject("", "", "", "")).andReturn(true);
    
        PowerMock.replay(SVNPlugin.class,svnPlugin);
    
        SVNPlugin svnplugin = SVNPlugin.getInstance();
        boolean checkOutFlg = svnplugin.getSynProject("", "", "", "");
        assertTrue(checkOutFlg);
    
        PowerMock.verify(svnPlugin,SVNPlugin.class);
      }
    }