使用 PHPUnit 和 Selenium 设置测试

2024-04-18

您能帮我设置测试环境吗? 我在 Ubuntu 上运行,安装了(并运行)selenium Web 服务器,并通过 PHPUnit 执行我的测试。 最有可能的是我陷入了一些小错误,但我现在不知道如何修复它。

我的代码很简单

class WebTest extends PHPUnit_Extensions_Selenium2TestCase 
{
protected function setUp()

{
    $this->setBrowser('firefox');
    $this->setBrowserUrl('http://www.google.com/');
}

public function testTitle()
{
    $this->url('http://www.google.com/');
    $this->assertEquals('google', $this->title());
}

但出现这个错误

PHP 致命错误:在第 4 行 /home/jozef/vendor/phpunit/phpunit-selenium/WebTest.php 中找不到类“PHPUnit_Extensions_Selenium2TestCase”

我已经安装了硒

你能帮我继续前进吗?谢谢 :)


以下是如何在 phpUnit、MacOS、laravel 5.2、firefox 上运行在 Firefox 上记录的 Selenium IDE 测试的说明。我还展示了如何在此处设置屏幕截图(我还设置了 Laravel 以访问数据库以在测试结束后清理它):

在您的 test-s 目录中,创建selenium目录。并创建文件: SeleniumClearTestCase.php

class SeleniumClearTestCase extends MigrationToSelenium2 // Because seleniumIDE tests are written in old format (selenium 1) so we use this adapter
    {
        protected $baseUrl = 'http://yourservice.dev';
    
        protected function setUp()
        {
            $screenshots_dir = __DIR__.'/screenshots';
            if (! file_exists($screenshots_dir)) {
                mkdir($screenshots_dir, 0777, true);
            }
            $this->listener = new PHPUnit_Extensions_Selenium2TestCase_ScreenshotListener($screenshots_dir);
    
            $this->setBrowser('firefox');
            $this->setBrowserUrl($this->baseUrl);
            $this->createApplication(); // bootstrap laravel app
        }
    
        public function onNotSuccessfulTest($e)
        {
            $this->listener->addError($this, $e, null);
            parent::onNotSuccessfulTest($e);
        }
    
        /**
         * Make screenshot.
         * @return
         */
        public function screenshot()
        {
            $this->listener->addError($this, new Exception, null); // this function create screenshot
        }
    
        /**
         * Creates the application.
         *
         * @return \Illuminate\Foundation\Application
         */
        public function createApplication()
        {
            $app = require __DIR__.'/../../bootstrap/app.php';
    
            $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
    
            return $app;
        }
    }

下一个文件:MigrationToSelenium2.php(来自 github,但我添加了一些修改):

    <?php
    /*
     * Copyright 2013 Roman Nix
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    /**
     * Implements adapter for migration from PHPUnit_Extensions_SeleniumTestCase
     * to PHPUnit_Extensions_Selenium2TestCase.
     *
     * If user's TestCase class is implemented with old format (with commands
     * like open, type, waitForPageToLoad), it should extend MigrationToSelenium2
     * for Selenium 2 WebDriver support.
     */
    abstract class MigrationToSelenium2 extends LaravelTestCase // MY modification - extends diffrent class. If you don't want use laravel, extends this class by PHPUnit_Extensions_Selenium2TestCase
    {
        public function open($url)
        {
            $this->url($url);
        }
    
        public function type($selector, $value)
        {
            $input = $this->byQuery($selector);
            $input->value($value);
        }
    
        protected function byQuery($selector)
        {
            if (preg_match('/^\/\/(.+)/', $selector)) {
                /* "//a[contains(@href, '?logout')]" */
                return $this->byXPath($selector);
            } elseif (preg_match('/^([a-z]+)=(.+)/', $selector, $match)) {
                /* "id=login_name" */
                switch ($match[1]) {
                    case 'id':
                        return $this->byId($match[2]);
                        break;
                    case 'name':
                        return $this->byName($match[2]);
                        break;
                    case 'link':
                        return $this->byPartialLinkText($match[2]);
                        break;
                    case 'xpath':
                        return $this->byXPath($match[2]);
                        break;
                    case 'css':
                        $cssSelector = str_replace('..', '.', $match[2]);
    
                        return $this->byCssSelector($cssSelector);
                        break;
    
                }
            }
            throw new Exception("Unknown selector '$selector'");
        }
    
        protected function waitForPageToLoad($timeout)
        {
            $this->timeouts()->implicitWait((int) $timeout); // MY modification - cast to 'int'
        }
    
        public function click($selector)
        {
            $input = $this->byQuery($selector);
            $input->click();
        }
    
        public function select($selectSelector, $optionSelector)
        {
            $selectElement = parent::select($this->byQuery($selectSelector));
            if (preg_match('/label=(.+)/', $optionSelector, $match)) {
                $selectElement->selectOptionByLabel($match[1]);
            } elseif (preg_match('/value=(.+)/', $optionSelector, $match)) {
                $selectElement->selectOptionByValue($match[1]);
            } else {
                throw new Exception("Unknown option selector '$optionSelector'");
            }
        }
    
        public function isTextPresent($text)
        {
            if (strpos($this->byCssSelector('body')->text(), $text) !== false) {
                return true;
            } else {
                return false;
            }
        }
    
        public function isElementPresent($selector)
        {
            $element = $this->byQuery($selector);
            if ($element->name()) {
                return true;
            } else {
                return false;
            }
        }
    
        public function getText($selector)
        {
            $element = $this->byQuery($selector);
    
            return $element->text();
        }
    
        /** MY MODIFICATION (support for getEval)
         * Function execute javascript code and is used in selenium IDE tests e.g. in function 'storeEval'.
         * @param  string $javascriptCode is JS Code e.g. "storedVars['registerurl'].match(/[^\\/]+$/)"
         * @param  [type] $args           associative array key-value which shoud be set in storedVars. e.g.
         *                                $args=['registerurl'=>'http://example.com']
         * @return string or array        if JS result is string/number then return it
         *                   							if JS result is array then return array.
         */
        public function getEval($javascriptCode, $args)
        {
            $sv = 'storedVars=[]; ';
            foreach ($args as $key => $val) {
                $sv = $sv."storedVars['".$key."']='".$val."'; ";
            }
    
            $result = $this->execute(['script' => $sv.' return '.$javascriptCode, 'args' => []]);
    
            return $result;
        }
    }

下一个文件:LaravelTestCase.php 这是 Illuminate\Foundation\Testing\TestCase 的精确副本,但它不扩展 PHPUnit_Framework_TestCase,而是扩展 PHPUnit_Extensions_Selenium2TestCase 类。

最后一个文件:在测试目录中创建文件testrunner(这是 bash 脚本):

seleniumIsRun=`ps | grep -w selenium.jar | grep -v grep | wc -l`
if (( $seleniumIsRun == 0 )); then    # run selenium server if it is not run already
    java -jar ./tests/selenium/selenium.jar &
    sleep 5s
fi
rm -r ./tests/selenium/screenshots
php artisan db:seed    # reset DB using laravel (my laravel seeders clean db at the begining)
vendor/bin/phpunit  # run php unit (in laravel it is in this direcotry)

下一步,从下载最新的“Selenium Standalone Server”http://www.seleniumhq.org/download/ http://www.seleniumhq.org/download/并更改其名称并将其复制到tests/selenium/selenium.jar。

下一步,如果您没有java控制台中的命令安装最新的 JDKhttp://www.oracle.com/technetwork/java/javase/downloads/index.html http://www.oracle.com/technetwork/java/javase/downloads/index.html

LARAVEL

在composer.json更新部分(添加:phpunit/phpunit-selenium (github) 和我们的新类)

    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "symfony/css-selector": "2.8.*|3.0.*",
        "symfony/dom-crawler": "2.8.*|3.0.*",
        "phpunit/phpunit-selenium": "> 1.2"
    },

    "autoload-dev": {
        "classmap": [
            "tests/selenium/SeleniumClearTestCase.php",
            "tests/selenium/MigrationToSelenium2.php",
            "tests/selenium/LaravelTestCase.php",
            "tests/TestCase.php"
        ]
    },

Then run

composer update

and

composer dump-autoload

好的,现在我们有了设置 selenium 和 phpunit 的所有文件。因此,让我们在 Firefox 中使用插件 Selenium IDE 进行一些测试,我们还需要安装“Selenium IDE:PHP Formatters”插件以将测试保存为 phpunit。当我们记录测试时,我们检查它是否有效,并将其保存为 phpunit (我们还可以将测试保存为本机 html selenium 格式 .se - 以获得 php 测试的“源”,并能够在将来运行它在 selenium IDE 中手动在 futre...) - 然后我们将其复制到文件夹 test/selenium/tests。然后我们通过删除 setUp 部分来更改测试,并将扩展类更改为SeleniumClearTestCase。例如我们可以像这样创建测试:

    <?php
    
    class LoginTest extends SeleniumClearTestCase
    {
        public function testAdminLogin()
        {
            self::adminLogin($this);
        }
    
        public function testLogout()
        {
            self::adminLogin($this);
    
            //START POINT: User zalogowany
            self::logout($this);
        }
    
        public static function adminLogin($t)
        {
            self::login($t, '[email protected] /cdn-cgi/l/email-protection', 'secret_password');
            $t->assertEquals('Jan Kowalski', $t->getText('css=span.hidden-xs'));
        }
    
        // @source LoginTest.se
        public static function login($t, $login, $pass)
        {
            $t->open('/');
            $t->click("xpath=(//a[contains(text(),'Panel')])[2]");
            $t->waitForPageToLoad('30000');
            $t->type('name=email', $login);
            $t->type('name=password', $pass);
            $t->click("//button[@type='submit']");
            $t->waitForPageToLoad('30000');        
        }
    
        // @source LogoutTest.se
        public static function logout($t)
        {
            $t->click('css=span.hidden-xs');
            $t->click('link=Wyloguj');
            $t->waitForPageToLoad('30000');
            $t->assertEquals('PANEL', $t->getText("xpath=(//a[contains(text(),'Panel')])[2]"));
        }
    }

正如您所看到的,我将可重复使用的部分放在单独的静态函数中。下面是使用静态函数的更复杂的测试(这也清理了数据库):

    <?php
    use App\Models\Device;
    use App\Models\User;
    
    class DeviceRegistrationTest extends SeleniumClearTestCase
    {
        public function testDeviceRegistration()
        {
          $email = '[email protected] /cdn-cgi/l/email-protection';
          self::registerDeviceAndClient($this,'Paris','Hilton',$email,'verydifficultpassword');
          self::cleanRegisterDeviceAndClient($email);
        }
    
        // ------- STATIC elements
    
        public static function registerDeviceAndClient($t,$firstname, $lastname, $email, $pass) {
          LoginTest::adminLogin($t);
    
          // START POINT: User zalogowany jako ADMIN
          $t->click('link=Urządzenia');
          $t->click('link=Rejestracja');
          $t->waitForPageToLoad('30000');
          $registerurl = $t->getText('css=h4');
          $token = $t->getEval("storedVars['registerurl'].match(/[^\\/]+$/)", compact('registerurl'))[0];
          $t->screenshot();
                             // LOG OUT ADMIn
          LoginTest::logout($t);
                            // Otwórz link do urzadzenia
          $t->open($registerurl);
          $t->click('link=Rejestracja');
          $t->waitForPageToLoad('30000');
          $t->type('name=email', $email);
          $t->screenshot(); // take some photo =)
          $t->click('css=button.button-control');
          $t->waitForPageToLoad('30000');
          // Symuluj klikniecie w link aktywacyjny z emaila
          $t->open('http://yourdomain.dev/rejestracja/'.$token);
          $t->type('name=firstname', $firstname);
          $t->type('name=lastname', $lastname);
          $t->type('name=password', $pass);
          $t->type('name=password_confirmation', $pass);
          $t->screenshot(); // powinno byc widac formularz rejestracyjny nowego klienta
          $t->click("//button[@type='submit']");
          $t->waitForPageToLoad('30000');
          // Asercje
          $t->assertEquals($firstname.' '.$lastname, $t->getText('css=span.hidden-xs'));
        }
    
        public static function cleanRegisterDeviceAndClient($email) {
          $user = User::where('email','=',$email)->first();
          $device = Device::where('client_user_id','=',$user->id);
          $device->forceDelete();
          $user->forceDelete();
        }
    }

你运行测试

./testrunner

enjoy :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 PHPUnit 和 Selenium 设置测试 的相关文章

随机推荐

  • 在 pandas 中的列元素旁边添加数值

    这是我问的问题的进一步部分here https stackoverflow com questions 51574485 match keywords in pandas column with another list of elemen
  • 使用 HTML 输入类型文件从网络摄像头捕获摄像机录制视频

    在我的公司 我的任务是建立一个网站 用户可以在其中录制视频 这将被发送到服务器 一些事情将被完成 用户最终会收到一封电子邮件 嵌入该视频的微型网站的链接 经过一番研究 我得出的结论是 至少目前这是不可能的 在 iPad 上使用 getUse
  • typescript 参数可以注释为 const 吗?

    如果我不希望函数作用域内的参数值发生变化 有什么方法可以用 Typescript 对其进行注释吗 我试过了 function walk const fileName string string 但这不起作用 现在没有办法做到 也可能做不到
  • 应用程序崩溃后套接字仍在侦听

    我在 Windows 2008x64 上使用我的 C 应用程序之一时遇到问题 同一应用程序在 Windows 2003x64 上运行得很好 崩溃后 甚至有时在定期关闭 重新启动周期后 使用端口 82 上的套接字时会出现问题 它需要接收命令
  • 计算字符串中的常见字符 Python

    该代码的输出仍然是 4 但是 输出应该是 3 存在集合交集 因为我相信这是答案的关键 答案是 4 而不是 3 的原因来自于 s1 中与 s2 匹配的 2 个 qs 和 1 个 r 的数量 s2 qsrqq s1 qqtrr counts1
  • 未选择值的 DropDownList

    我在编辑页面内使用 DropDownListFor 辅助方法 但没有运气让它选择我指定的值 我注意到一个类似的问题 https stackoverflow com questions 1916462 dropdownlistfor in e
  • 有没有办法在 Azure DevOps Pipelines YAML 中参数化/动态设置变量组名称?

    我有一个嵌套的 Azure DevOps YAML 管道 name Some Release Pipeline trigger none variables group DEV VARIABLE GROUP This is the envi
  • 从 PHP 脚本调用节点

    我正在尝试使用 PHP 脚本调用节点脚本exec output exec usr bin node home user nodescript js nodescript js 是 var Scraper require google ima
  • Mac OSX 捆绑包的图标

    我编译了一个名为 MyBundle bundle 的 Mac OSX 捆绑包 它用作另一个应用程序的插件 我希望捆绑包有一个独特的图标 因此我将 Info plist 文件设置为
  • AspectJ 是如何工作的?

    我正在尝试了解 Aspect 的工作原理 我有 C C 背景 但魔法永远不会发生 我知道你可以用注释一些函数 Aspect然后写下Aspect的实现等等 但是 新代码是如何 以及在 什么时间 生成的 假设我没有编辑器 我使用编译java类j
  • elasticsearch中@timestamp和timestamp字段的区别

    当我使用日志存储向弹性搜索记录一些请求时 它将 timestamp 字段作为时间 当我使用 NEST 记录这些请求并设置时间戳字段时 它会放置时间戳字段 当我使用 kibana 查看数据时 这两个字段具有单独的名称 他们之间有什么区别 ti
  • 使用“-prune”时,从“find”命令中省略“-print”

    我一直无法完全理解 find 命令的 prune 操作 但实际上 至少我的一些误解源于省略 print 表达的影响 从 查找 手册页 如果表达式除 prune 之外不包含任何操作 则对表达式为 true 的所有文件执行 print 我一直
  • 使用 Tkinter 将鼠标悬停在文本上时更改文本颜色?

    所以我在 Tkinter 的画布上有一堆文本 我想让它在鼠标悬停在文本上时文本颜色发生变化 对于我的生活 我不知道如何做到这一点 并且似乎没有很多关于 Tkinter 的信息 for city in Cities CityText Citi
  • 优化康威的“生命游戏”

    为了进行实验 我 很久以前 实施了康威的生命游戏 http en wikipedia org wiki Conway s Game of Life 而且我知道this https stackoverflow com questions 18
  • Tkinter 主窗口焦点

    我有以下代码 window Tk window lift window attributes topmost True 这段代码的工作原理是将我的 Tkinter 窗口显示在所有其他窗口之上 但它仍然只解决了一半的问题 虽然该窗口实际上显示
  • 将 lambda 函数应用于 dask 数据框

    我正在寻找申请lambda如果列中的标签小于一定百分比 则使用 dask 数据框的函数来更改列中的标签 我使用的方法适用于 pandas 数据框 但相同的代码不适用于 dask 数据框 代码如下 df pd DataFrame A ant
  • 将多个单元格添加到单行

    我对此很陌生 当我尝试将多个单元格添加到一行时 它说有不可读的内容 这是我所拥有的 SpreadsheetDocument ssDoc SpreadsheetDocument Create saveFile SpreadsheetDocum
  • 作为单独用户运行应用程序的最佳初始化脚本

    我有一个在用户帐户 基于 Plack 中运行的应用程序 并且需要一个初始化脚本 它看起来就像 sudo user start server 一样简单 我刚刚使用 start stop daemon 编写了一个 LSB 脚本 它确实很笨拙且冗
  • Apple HLS 中的 PES 数据包内的访问单元如何对齐?

    Apple 是否指定了这一点 PES 数据包有效负载中应放置多少个访问单元 另外 我想知道 PES 数据包中存在哪些前缀起始代码 如果有 我认为访问单元中第一个 NAL 单元之前的单元是无用的 不能放置 正确的 我想知道它是如何在 HLS
  • 使用 PHPUnit 和 Selenium 设置测试

    您能帮我设置测试环境吗 我在 Ubuntu 上运行 安装了 并运行 selenium Web 服务器 并通过 PHPUnit 执行我的测试 最有可能的是我陷入了一些小错误 但我现在不知道如何修复它 我的代码很简单 class WebTest