how do i mock the a static method that provides an instance of the class being mocked with JMockit?

核能气质少年 提交于 2019-12-11 13:41:38

问题


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());


来源:https://stackoverflow.com/questions/36753107/how-do-i-mock-the-a-static-method-that-provides-an-instance-of-the-class-being-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!