how do i mock the a static method that provides an

2019-07-25 13:14发布

问题:

I'm trying to mock a singleton class (SessionDataManager) where I get an instance by calling the static getInstance() method but all attempts seem to return null.

I've tried

    @Mocked SessionDataManager sessionDataManager;

or

        new MockUp<SessionDataManager>(){
            @Mock
            public SessionDataManager getInstance(Invocation invocation) {

                return invocation.getInvokedInstance(); 
            }
        };

I get the same result = null;

Can anyone suggestion a solution?

Thanks

回答1:

I would suggest having a look at the documentation, but here are two complete example tests:

public final class ExampleTest {
    public static final class SessionDataManager {
        private static final SessionDataManager instance = new SessionDataManager();
        public static SessionDataManager getInstance() { return instance; }
        public void doSomething() { throw new UnsupportedOperationException("to do"); }
    }

    @Test
    public void mockingASingleton(@Mocked SessionDataManager mockInstance) {
        SessionDataManager singletonInstance = SessionDataManager.getInstance();

        assertSame(mockInstance, singletonInstance);
        singletonInstance.doSomething(); // mocked, won't throw
    }

    @Test
    public void mockingASingletonWithAMockUp() {
        new MockUp<SessionDataManager>() {
            // no point in having a @Mock getInstance() here
            @Mock void doSomething() { /* whatever */ }
        };

        SessionDataManager singletonInstance = SessionDataManager.getInstance();
        singletonInstance.doSomething(); // redirects to the @Mock method, won't throw
    }
}


回答2:

Take a look at Expectations' class:

new Expectations() {

    Singleton singleton;
    {
        Singleton.getInstance(); returns(singleton);
        singleton.valueFromSingleton(); returns(1);
    }
};

Entity entity = new Entity();
assertEquals(1, entity.valueFromEntity());