簡體   English   中英

使用 PowerMock 在靜態塊中模擬 getResource

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM