1

I want to test the ClassToTest class for it's method methodToTest. But I am not able to make it as the private method anotherMethod which is being called by the methodToTest has some dependency with the value returned by the singleton class SingletonClass using its public method getName.

I tried using powermock's privateMethod mock and static method mock and all, but no help.
Does anyone have a solution for this scenario?

Class ClassToTest{
    public void methodToTest(){
        ...
        anotherMethod();
        ...
    }

    private void anotherMethod(){
        SingletonClass singletonObj = SingletonClass.getInstance();
        String name = singletonObj.getName();
        ...
    }
}
Jeff
  • 12,555
  • 5
  • 33
  • 60
  • duplicate ? [see this](http://stackoverflow.com/questions/2302179/mocking-a-singleton-class). Alternatively if you are able to modify the ClassToTest (?) it would be favorable to weaken the dependency on the singleton. – Pyranja Jan 25 '13 at 00:07

2 Answers2

0

Use mockStatic (see http://code.google.com/p/powermock/wiki/MockitoUsage13#Mocking_Static_Method)

@RunWith(PowerMockRunner.class)
@PrepareForTest({SingletonClass.class})
public class ClassToTestTest {
    @Test
    public void testMethodToTest() {
        SingletonClass mockInstance = PowerMockito.mock(SingletonClass.class);
        PowerMockito.mockStatic(SingletonClass.class);
        PowerMockito.when(SingletonClass.getInstance()).thenReturn(mockInstance);
        PowerMockito.when(mockInstance.getName()).thenReturn("MOCK NAME");

        //...
    }
}
Matt Lachman
  • 4,541
  • 3
  • 30
  • 40
0

You should be able to use a partial mock to deal with this situation. It sounds like you want to create an instance of the object, but you just want to see if the object calls the anotherMethod() method without actually doing any of the logic in the other method. If I'm understanding correctly, the following should accomplish your goal.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToTest.class})
public class ClassToTestTest {
    @Test
    public void testMethodToTest() {
        ClassToTest mockInstance = 
                   PowerMock.createPartialMock(SingletonClass.class,"anotherMethod");
        PowerMock.expectPrivate(mockInstance, "anotherMethod");
        PowerMock.replay(mockInstance);
        mockInstance.methodToTest();
        PowerMock.verify(mockInstance);
    }
}
HardcoreBro
  • 425
  • 4
  • 17