Mocking a singleton with mockito

后端 未结 7 1075
别跟我提以往
别跟我提以往 2020-12-08 00:50

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.

7条回答
  •  春和景丽
    2020-12-08 01:03

    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.

提交回复
热议问题