Espresso:如何在WebView上调用evaluateJavascript()

时间:2016-07-14 17:08:55

标签: android android-espresso

我正在尝试获取WebView的实例,以便我可以在其上调用evaluateJavascript()。 我编写了一个自定义匹配器,然后尝试将WebView分配给静态变量,如下所示:

 public static WebView view1;

 public static Matcher<View> isJavascriptEnabled1() {
    return new BoundedMatcher<View, WebView>(WebView.class) {
        @Override
        public void describeTo(Description description) {
            description.appendText("WebView with JS enabled");
        }
        @Override
        public boolean matchesSafely(WebView webView) {
            view1 =webView;
            return webView.getSettings().getJavaScriptEnabled();
        }
    };
}

在我的测试课中,我打电话给:

 CustomMatcher.isJavascriptEnabled1();
 CustomMatcher.view1.evaluateJavascript("$('.status dl       dd').get(0).innerText.replace('pts.', '').replace(',', '').trim()\"]",new    ValueCallback<String>() {
   @Override
   public void onReceiveValue(String s) {
       Log.d("LogName", s); // Prints asd
   }

});

我收到错误:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.evaluateJavascript(java.lang.String, android.webkit.ValueCallback)' on a null object reference

1 个答案:

答案 0 :(得分:5)

您没有使用Matcher来匹配视图。它无法正常工作,因为调用isJavascriptEnabled1()只会创建自定义Matcher的新实例。但是例如永远不会执行matchesSafely(),这就是CustomMatcher.view1null的原因。 要使代码生效,您必须将Espresso.onView()Matcher

一起使用
 // Use onView and the matcher to find a web view with enabled java script
 Espresso.onView(CustomMatcher.isJavascriptEnabled1());

 // Now CustomMatcher.view1 should not be null (if there is a web view)
 CustomMatcher.view1.evaluateJavascript("$('.status dl       dd').get(0).innerText.replace('pts.', '').replace(',', '').trim()\"]",new    ValueCallback<String>() {
   @Override
   public void onReceiveValue(String s) {
       Log.d("LogName", s); // Prints asd
   }
});

但那仍然不正确。方法evaluateJavascript()是异步的,Espresso不会等待回调(onReceiveValue())。因此,测试很可能在调用onReceive()之前完成。

还有Espresso Web用于测试WebViews。根据您的目标,您可能会发现它很有用。 Espresso Web也在幕后执行java脚本。

如果不使用Espresso Web,我建议您编写一份自定义ViewAction,将在匹配的WebView上执行。此操作可以使用WebView来评估java脚本:

/**
 * {@link ViewAction} that evaluates javascript in a {@link WebView}.
 */
public class EvaluateJsAction implements ViewAction, ValueCallback<String> {

    private static final long TIME_OUT = 5000;
    private final String mJsString;
    private final AtomicBoolean mEvaluateFinished = new AtomicBoolean(false);

    public EvaluateJsAction(final String javaScriptString) {
        mJsString = javaScriptString;
    }

    @Override
    public Matcher<View> getConstraints() {
        return isAssignableFrom(WebView.class);
    }

    @Override
    public String getDescription() {
        return "evaluate '" + mJsString + "' on webview";
    }

    @Override
    public void perform(UiController uiController, View view) {
        uiController.loopMainThreadUntilIdle();

        final WebView webView = (WebView) view;
        webView.evaluateJavascript(mJsString, this);

        final long timeOut = System.currentTimeMillis() + TIME_OUT;
        while (!mEvaluateFinished.get()) {
            if (timeOut < System.currentTimeMillis()) {
                throw new PerformException.Builder()
                        .withActionDescription(this.getDescription())
                        .withViewDescription(HumanReadables.describe(view))
                        .withCause(new RuntimeException(String.format(Locale.US,
                                "Evaluating java script did not finish after %d ms of waiting.", TIME_OUT)))
                        .build();
            }
            uiController.loopMainThreadForAtLeast(50);
        }
    }

    @Override
    public void onReceiveValue(String value) {
        mEvaluateFinished.set(true);
    }
}

然后使用此操作:

onView(withJavaScriptEnabled()).perform(new EvaluateJsAction(theJavaScriptString));