简体   繁体   中英

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

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

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
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM