作为我的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}}
答案 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);
}
}