使用没有受限标头的HttpURLConnection进行测试

时间:2018-02-08 17:46:52

标签: java testing mocking

作为我的JUnit测试套件的一部分,我必须测试使用HttpURLConnection个限制标头之一发送HTTP请求。

conn.setRequestProperty("Host", host);

@BeforeTest我可以允许受限制的标题,但是当事先执行类的静态初始化程序时,这将不起作用:

@BeforeClass
public static void init() {
    // this won't work because HttpURLConnection has already been initialized
    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}

允许限制标头的另一种方法是什么?{... 1}}

1 个答案:

答案 0 :(得分:0)

由于我们已经在使用PowerMockito,因此我最终使用Whitebox功能修改了restrictedHeaderSet私有静态最终字段:

@RunWith(PowerMockRunner.class)
public class ServerTest {

    private static Set<String> restrictedHeaderSetBackup;

    @BeforeClass
    public static void setup() throws Exception {
        Set<String> original = getRestrictedHeaderSet();
        restrictedHeaderSetBackup = new HashSet<>(original);
        original.clear();
    }

    @AfterClass
    public static void tearDown() throws Exception {
        Set<String> modified = getRestrictedHeaderSet();
        modified.addAll(restrictedHeaderSetBackup);
    }

    private static Set<String> getRestrictedHeaderSet() throws Exception {
        return (Set<String>) Whitebox.getAllStaticFields(HttpURLConnection.class)
                .stream()
                .filter(f -> f.getName().equals("restrictedHeaderSet"))
                .findFirst()
                .get()
                .get(HttpURLConnection.class);
    }
}