44
votes

I need to test some legacy code, which uses a singleton in a a method call. The purpose of the test is to ensure that the clas sunder test makes a call to singletons method. I have seen similar questions on SO, but all the answers require other dependencies (different test frameworks) - I'm unfortunately limited to using Mockito and JUnit, but this should be perfectly possible with such popular framework.

The singleton:

public class FormatterService {

    private static FormatterService INSTANCE;

    private FormatterService() {
    }

    public static FormatterService getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new FormatterService();
        }
        return INSTANCE;
    }

    public String formatTachoIcon() {
        return "URL";
    }

}

The class under test:

public class DriverSnapshotHandler {

    public String getImageURL() {
        return FormatterService.getInstance().formatTachoIcon();
    }

}

The unit test:

public class TestDriverSnapshotHandler {

    private FormatterService formatter;

    @Before
    public void setUp() {

        formatter = mock(FormatterService.class);

        when(FormatterService.getInstance()).thenReturn(formatter);

        when(formatter.formatTachoIcon()).thenReturn("MockedURL");

    }

    @Test
    public void testFormatterServiceIsCalled() {

        DriverSnapshotHandler handler = new DriverSnapshotHandler();
        handler.getImageURL();

        verify(formatter, atLeastOnce()).formatTachoIcon();

    }

}

The idea was to configure the expected behaviour of the dreaded singleton, since the class under test will call it's getInstance and then formatTachoIcon methods. Unfortunately this fails with an error message:

when() requires an argument which has to be 'a method call on a mock'.
8
You can't do this in Mockito, without also using PowerMock, unless you refactor one of your classes. But I'm not sure why you want to. You're unit testing a method with just one line, and no internal logic. This can't fail. Spend your testing effort elsewhere.Dawood ibn Kareem
"The purpose of the test is to ensure that the clas sunder test makes a call to singletons method." No good test case should have this kind of thing as its purpose. Instead, aim to test some meaningful business functionality. Mocking a dependency and verifying a method is called is not necessarily wrong, but it should be done only when needed.Rogério
all these ways just cause headaches...they work for static methods but if its a method of the instance and its referencing a class variable it will get null pointer right ? but powerMockito is one way. instead just do what do we in the old days, make y our singleTon implement an interface. then in your test use the interface which just has all stubs in it. reference: stackoverflow.com/a/17325647/835883j2emanue
@fbielejec what is inside mock method?codeSeeker

8 Answers

39
votes

What you are asking is not possible because your legacy code relies on a static method getInstance() and Mockito does not allow to mock static methods, so the following line won't work

when(FormatterService.getInstance()).thenReturn(formatter);

There are 2 ways around this problem:

  1. Use a different mocking tool, such as PowerMock, that allows to mock static methods.

  2. Refactor your code, so that you don't rely on the static method. The least invasive way I can think of to achieve this is by adding a constructor to DriverSnapshotHandler that injects a FormatterService dependency. This constructor will be only used in tests and you production code will continue to use the real singleton instance.

    public static class DriverSnapshotHandler {
    
        private final FormatterService formatter;
    
        //used in production code
        public DriverSnapshotHandler() {
            this(FormatterService.getInstance());
        }
    
        //used for tests
        DriverSnapshotHandler(FormatterService formatter) {
            this.formatter = formatter;
        }
    
        public String getImageURL() {
            return formatter.formatTachoIcon();
        }
    }
    

Then, your test should look like this :

FormatterService formatter = mock(FormatterService.class);
when(formatter.formatTachoIcon()).thenReturn("MockedURL");
DriverSnapshotHandler handler = new DriverSnapshotHandler(formatter);
handler.getImageURL();
verify(formatter, atLeastOnce()).formatTachoIcon();
30
votes

I think it is possible. See an example how to test a singleton

Before a test:

@Before
public void setUp() {
    formatter = mock(FormatterService.class);
    setMock(formatter);
    when(formatter.formatTachoIcon()).thenReturn(MOCKED_URL);
}

private void setMock(FormatterService mock) {
    try {
        Field instance = FormatterService.class.getDeclaredField("instance");
        instance.setAccessible(true);
        instance.set(instance, mock);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

After the test - it is important to clean up the class, because other tests will be confused with the mocked instance.

@After
public void resetSingleton() throws Exception {
   Field instance = FormatterService.class.getDeclaredField("instance");
   instance.setAccessible(true);
   instance.set(null, null);
}

The test:

@Test
public void testFormatterServiceIsCalled() {
    DriverSnapshotHandler handler = new DriverSnapshotHandler();
    String url = handler.getImageURL();

    verify(formatter, atLeastOnce()).formatTachoIcon();
    assertEquals(MOCKED_URL, url);
}
4
votes

I just want to complete the solution from noscreenname. The solution is using PowerMockito. Because PowerMockito can do something like Mockito, So sometimes you can just use PowerMockito .

The example code is here:

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;


import java.lang.reflect.Field;

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Singleton.class})
public class SingletonTest {

    @Test
    public void test_1() {
        // create a mock singleton and change
        Singleton mock = mock(Singleton.class);
        when(mock.dosth()).thenReturn("succeeded");
        System.out.println(mock.dosth());

        // insert that singleton into Singleton.getInstance()
        PowerMockito.mockStatic(Singleton.class);
        when(Singleton.getInstance()).thenReturn(mock);
        System.out.println("result:" + Singleton.getInstance().dosth());
    }

}

Singleton class:

public class Singleton {

    private static Singleton INSTANCE;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }

    public String dosth() {
        return "failed";
    }

}

Here is my Gradle:

/*
*  version compatibility see: https://github.com/powermock/powermock/wiki/mockito
*
* */

def powermock='2.0.2'
def mockito='2.8.9'
...
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'

    /** mock **/
    testCompile group: 'org.mockito', name: 'mockito-core', version: "${mockito}"

    testCompile "org.powermock:powermock-core:${powermock}"
    testCompile "org.powermock:powermock-module-junit4:${powermock}"
    testCompile "org.powermock:powermock-api-mockito2:${powermock}"
    /**End of power mock **/

}
1
votes

Your getInstance Method is static, thus can't be mocked using mockito. http://cube-drone.com/media/optimized/172.png. You might want to use PowerMockito to do so. Although I would not recommend doing it this way. I would test DriverSnapshotHandler via dependency injection:

public class DriverSnapshotHandler {

    private FormatterService formatterService;

    public DriverSnapshotHandler(FormatterService formatterService) {
        this.formatterService = formatterService;
    }

    public String getImageURL() {
        return formatterService.formatTachoIcon();
    }

}

The unit test:

public class TestDriverSnapshotHandler {

    private FormatterService formatter;

    @Before
    public void setUp() {

        formatter = mock(FormatterService.class);

        when(formatter.formatTachoIcon()).thenReturn("MockedURL");

    }

    @Test
    public void testFormatterServiceIsCalled() {

        DriverSnapshotHandler handler = new DriverSnapshotHandler(formatter);
        handler.getImageURL();

        verify(formatter, times(1)).formatTachoIcon();

    }

}

You might want to set the mock to null in a @After method. This is IMHO the cleaner solution.

0
votes

If it could helps someone This is my method to test singleton classes You just need to mock all your singleton class and then use doCallRealMethod to really call methods you want to test.

SingletonClass.java :

class SingletonClass {

    private static SingletonClass sInstance;

    private SingletonClass() {
        //do somethings
    }

    public static synchronized SingletonClass getInstance() {
        if (sInstance == null) {
            sInstance = new SingletonClass();
        }

        return sInstance;
    }

    public boolean methodToTest() {
        return true;
    }
}

SingletonClassTest.java :

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

public class SingletonClassTest {

    private SingletonClass singletonObject;

    @Before
    public void setUp() throws Exception {
        singletonObject = mock(SingletonClass.class);

        Mockito.doCallRealMethod().when(singletonObject).methodToTest();
    }

    @Test
    public void testMethodToTest() {
        assertTrue(singletonObject.methodToTest());
    }
}
0
votes

I have a workaround for mocking a Singleton class using reflection. While setting up your tests, you might consider doing the following.

@Mock 
private MySingletonClass mockSingleton;

private MySingletonClass originalSingleton;

@Before 
public void setup() {
    originalSingleton = MySingletonClass.getInstance();
    when(mockSingleton.getSomething()).thenReturn("Something"); // Use the mock to return some mock value for testing

    // Now set the instance with your mockSingleton using reflection 
    ReflectionHelpers.setStaticField(MySingletonClass.class, "instance", mockSingleton);
}

@After
public void tearDown() {
    // Reset the singleton object when the test is complete using reflection again
    ReflectionHelpers.setStaticField(MySingletonClass.class, "instance", null);
}

@Test
public void someTest() {
    // verify something here inside your test function.
}

The ReflectionHelpers is provided by Robolectric in Android. However, you can always write your own functions which can help you with this. You can check the question here to get an idea.

0
votes

As a beginner in Software Development, IMO, dependency injection of a singleton class in a driver/otherservice is a good option. As we can control creation of a single instance of the class and still be able to mock the static methods (as you might have guessed, I have util services in my mind) without using something like PowerMock to mock the static methods (IME which was little painful) I am very much open to listen about it from experienced folks from SOLID or Good OO design principle perspective.

public class DriverSnapshotHandler {
    private FormatterService formatter;
    public DriverSnapshotHandler() {
        this(FormatterService.getInstance());
    }
    public DriverSnapshotHandler (FormatterService formatterService){
           this.formatter = formatterService;
    }
    public String getImageURL() {
        return FormatterService.getInstance().formatTachoIcon();
    }
}

and then test using Mockito, something like this.

@Test
public void testGetUrl(){
  FormatterService formatter = mock(FormatterService.class);
  when(formatter.formatTachoIcon()).thenReturn("TestURL");
  DriverSnapshotHandler handler = new DriverSnapshotHandler(formatter);
  assertEquals(handler.getImageURL(), "TestUrl";
}
0
votes

You can use powermock/ reflection to change the value of instance variable itself.

FormatterService formatter = mock(FormatterService.class);
when(formatter.formatTachoIcon()).thenReturn("MockedURL");

// here use reflection or whitebox 

Whitebox.setInternalState(FormatterService.class, "INSTANCE", formatter);