[英]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. 我正在尝试模拟单例类(SessionDataManager),在其中我通过调用静态getInstance()方法获得实例,但是所有尝试似乎都返回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; 我得到相同的结果= 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: 看一下Expectations的课程:
new Expectations() {
Singleton singleton;
{
Singleton.getInstance(); returns(singleton);
singleton.valueFromSingleton(); returns(1);
}
};
Entity entity = new Entity();
assertEquals(1, entity.valueFromEntity());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.