public String getResponseAgain()
{
List<String> anotherArray = new ArrayList<>();
String[] extractedValue ={""};
page.onResponse(response -> {
if (response.url().contains("myUrlIsHere")) {
String value = response.url().substring(response.url().lastIndexOf("someValue") + 2,
response.url().indexOf("anotherValue"));
String[] splitText = value.split("bySomeValue");
List<String> arrayOfStrings = new ArrayList<>(Arrays.asList(splitText));
extractedValue[0] = String.join(" ", arrayOfStrings);
anotherArray.addAll(List.of(extractedValue));
for(String arr : anotherArray){
System.out.println("Arr is " + arr);
}
}
});
return anotherArray.get(0);
}
我在测试类中使用该方法:
public void responsesTest(){
////some code that accesses url and is ok////
Assertions.assertEquals("expected value", page.getResponseAgain());
}
这是可行并打印正确值的原始方法:
public void getSomeResponse(){
page.onResponse(response -> {
if (response.url().contains("myUrlIsHere")) {
String value = response.url().substring(response.url().lastIndexOf("someValue") + 2, response.url().indexOf("anotherValue"));
String[] splitText = value.split("bySomeValue");
List<String> arrayOfStrings = new ArrayList<>(Arrays.asList(splitText));
String extractedValue = String.join(" ", arrayOfStrings);
System.out.println(extractedValue);
}
});
}
您正在立即返回
anotherArray.get(0)
page.onResponse
仍然为空。您需要等待网络响应,然后再返回值(例如使用anotherArray
page.waitForResponse(...)