I创建了一个空隙方法,该方法从URL(使用Java和playwright)打印出所需的响应,但实际上我需要接收这些值以制作Junit断言,并且我试图将该方法转换为字符串方法,但我无法获得返回的值。

问题描述 投票:0回答:1

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(...)
java arraylist playwright
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.