[英]Mocking getResource in static block with PowerMock
如何在静态块中模拟 getResourceAsStream ? 我认为这是不可测试的。
我查看了 SO 并找不到答案。 closes-SO-post-here没有解决这个问题,因为在 post 中对 getResourceAsAStream 的调用不是来自静态块。
我尝试了 PowerMock,但遇到了许多限制。 首先,如果我想模拟SomeProperties.class.getResourceAsStream
- 静态块将执行,因为我需要引用类本身。 我可以抑制静态块以防止这样做,但这将阻止我完全执行静态块。 解决方案是将静态块的执行推迟到 someProperties.class.getResourceAsStream 被模拟之后。 我不认为这是可能的。 看来这段代码纯粹是不可测试的; 还有其他想法吗?
这是代码[和到 GITHUB 的链接] :
package com.sopowermock1;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SomeProperties {
private static Properties props = new Properties();
static {
InputStream is = SomeProperties.class.getResourceAsStream("/some.properties");
try {
props.load(is);
System.out.println("Properties.props.keySet() = " + props.keySet());
} catch (IOException e) {
// How test this branch???
System.out.println("Yes. We got here.");
throw new RuntimeException(e);
}
}
private SomeProperties() {}; // to makes life even harder...
public static String getVersion() {
return props.getProperty("version");
}
}
这是测试GITHUB 链接
package com.sopowermock1;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.sopowermock1.SomeProperties;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SomeProperties.class)
// This will prevent running static block completely:
// @SuppressStaticInitializationFor("com.sopowermock1.SomeProperties")
public class SomePropertiesTest {
@Mock
private static InputStream streamMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(SomeProperties.class);
System.out.println("test setUp");
}
@Test(expected = RuntimeException.class)
public void testStaticBlock() {
PowerMockito.mockStatic(SomeProperties.class); // this will mock all static methods (unwanted as we want to call getVersion)
// This will cause static block to be called.
PowerMockito.when(SomeProperties.class.getResourceAsStream("/some.properties")).thenReturn(streamMock);
SomeProperties.getVersion();
}
}
有任何想法吗?。 完整的 GITHUB 源代码在这里。
如如何使用 PowerMockito 和 JUnit 模拟 getResourceAsStream 方法中所述? ,使用Extract Delegate ,然后模拟XXStreamFetcher等委托类,然后就可以测试了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.