我如何模拟一个静态方法,它提供了一个用 JMockit 模拟的 class 的实例?

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

我正在尝试模拟一个单例 class (SessionDataManager),我通过调用静态 getInstance() 方法获取一个实例,但所有尝试似乎都 return 为空。

我试过了

    @Mocked SessionDataManager sessionDataManager;

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

                return invocation.getInvokedInstance(); 
            }
        };

我得到相同的结果 = null;

谁能提出解决方案?

谢谢

看看期望值'class:

new Expectations() {

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

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

我建议看一下 documentation,但这里有两个完整的示例测试:

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