草庐IT

php - 使用 PHPUnit 和 Selenium 设置测试

coder 2024-04-28 原文

你能帮我设置我的测试环境吗? 我在 Ubuntu 上运行,安装(并运行)了 selenium 网络服务器,并使用 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 Fatal error: Class 'PHPUnit_Extensions_Selenium2TestCase' not found in /home/jozef/vendor/phpunit/phpunit-selenium/WebTest.php on line 4

我已经安装了Selenium

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

最佳答案

这里是如何在 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)

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

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

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"
        ]
    },

然后运行

composer update

composer dump-autoload

好的,现在我们拥有了设置 selenium 和 phpunit 的所有文件。因此,让我们在 firefox 中使用插件 Selenium IDE 进行一些测试,我们还需要安装“Selenium IDE: PHP Formatters”插件以将测试保存为 phpunit。当我们记录测试时,我们检查它是否工作并将其保存为 phpunit(我们也可以将测试保存为 native html selenium 格式 .se - 拥有我们的 php 测试的“源代码”,并能够在未来运行它在 selenium IDE 中手动在未来......) - 然后我们将它复制到文件夹 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, 'jan.kowalski@gmail.com', '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]"));
        }
    }

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

    <?php
    use App\Models\Device;
    use App\Models\User;
    
    class DeviceRegistrationTest extends SeleniumClearTestCase
    {
        public function testDeviceRegistration()
        {
          $email = 'paris@gmail.com';
          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

享受:)

关于php - 使用 PHPUnit 和 Selenium 设置测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845828/

有关php - 使用 PHPUnit 和 Selenium 设置测试的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐