【亲测】Appium测试Android混合应用时,第二次切换到WebView失败

要解决的问题:Appium测试Android混合应用时,第二次切换到WebView时失败

原因分析:在用Appium测试Android混合应用时,当程序第一次切换到WebView时,可以正常进行自动化测试。可是当程序第二次切换到WebView时,Appium会自动找到到第一次打开的Html页面,那么这时Appium就无法定位我们第二次打开的Html页面中的元素。

                 Appium第一次切换到Html页面时,会新生成一个Chromedriver;当第二次切换到Html时,会使用已经存在的Chromedriver。但其实在我们的应用里面每次打开一个Activity时一般都是会重新创建一个WebChromeClient,所以这里就把它改成无论如何都生成一个新的Chromedriver。

解决步骤:修改Appium源码

      Appium安装目录下的文件

      Appium ode_modulesappiumlibdevicesandroidandroid-hybrid.js,文件中有这样一个函数:

      androidHybrid.startChromedriverProxy = function (context, cb) {
        cb = _.once(cb);
        logger.debug("Connecting to chrome-backed webview");
        if (this.chromedriver !== null) {
          return cb(new Error("We already have a chromedriver instance running"));
        }

        if (this.sessionChromedrivers[context]) {
          // in the case where we've already set up a chromedriver for a context,
          // we want to reconnect to it, not create a whole new one
          this.setupExistingChromedriver(context, cb);
        } else {
          this.setupNewChromedriver(context, cb);
        }
      };

      改为:

      androidHybrid.startChromedriverProxy = function (context, cb) {
        cb = _.once(cb);
        logger.debug("Connecting to chrome-backed webview");
        if (this.chromedriver !== null) {
          return cb(new Error("We already have a chromedriver instance running"));
        }

        // if (this.sessionChromedrivers[context]) {
        //   // in the case where we've already set up a chromedriver for a context,
        //   // we want to reconnect to it, not create a whole new one
        //   this.setupExistingChromedriver(context, cb);
        // } else {
        //   this.setupNewChromedriver(context, cb);
        // }
        this.setupNewChromedriver(context, cb);
      };
原文地址:https://www.cnblogs.com/imlvbu/p/7160142.html