你可以很容易地让 Selenium 等到一个特定的条件成立;就你所拥有的而言,一种选择是:
new FluentWait<JavascriptExecutor>(executor) {
protected RuntimeException timeoutException(
String message, Throwable lastException) {
Assert.fail("name was never set");
}
}.withTimeout(10, SECONDS)
.until(new Predicate<JavascriptExecutor>() {
public boolean apply(JavascriptExecutor e) {
return (Boolean)executor.executeScript("return ('Hello' === getName());");
}
});
但是,您基本上是在准确地测试您刚刚编码的内容,其缺点是如果在您调用 setName 之前设置了 name,则您不必等待 setName 完成。我过去为类似的事情做过的一件事是:
在我的测试库(用setTimeout shims 替换真正的异步调用)中,我有这个:
window._junit_testid_ = '*none*';
window._junit_async_calls_ = {};
function _setJunitTestid_(testId) {
window._junit_testid_ = testId;
}
function _setTimeout_(cont, timeout) {
var callId = Math.random().toString(36).substr(2);
var testId = window._junit_testid_;
window._junit_async_calls_[testId] |= {};
window._junit_async_calls_[testId][callId] = 1;
window.setTimeout(function(){
cont();
delete(window._junit_async_calls_[testId][callId]);
}, timeout);
}
function _isTestDone_(testId) {
if (window._junit_async_calls_[testId]) {
var thing = window._junit_async_calls_[testId];
for (var prop in thing) {
if (thing.hasOwnProperty(prop)) return false;
}
delete(window._junit_async_calls_[testId]);
}
return true;
}
在我的图书馆的其余部分,我使用_setTimeout_ 而不是window.setTimeout 来设置以后发生的事情。然后,在我的硒测试中,我做了这样的事情:
// First, this routine is in a library somewhere
public void waitForTest(JavascriptExecutor executor, String testId) {
new FluentWait<JavascriptExecutor>(executor) {
protected RuntimeException timeoutException(
String message, Throwable lastException) {
Assert.fail(testId + " did not finish async calls");
}
}.withTimeout(10, SECONDS)
.until(new Predicate<JavascriptExecutor>() {
public boolean apply(JavascriptExecutor e) {
return (Boolean)executor.executeScript(
"_isTestDone_('" + testId + "');");
}
});
}
// Inside an actual test:
@Test public void serverPingTest() {
// Do stuff to grab my WebDriver instance
// Do this before any interaction with the app
driver.executeScript("_setJunitTestid_('MainAppTest.serverPingTest');");
// Do other stuff including things that fire off what would be async calls
// but now call stuff in my testing library instead.
// ...
// Now I need to wait for all the async stuff to finish:
waitForTest(driver, "MainAppTest.serverPingTest");
// Now query stuff about the app, assert things if needed
}
请注意,如果需要,您可以多次调用waitForTest,只要您需要暂停该测试,直到所有异步操作完成。