【问题标题】:Set up tests with PHPUnit and Selenium使用 PHPUnit 和 Selenium 设置测试
【发布时间】:2016-02-24 01:42:11
【问题描述】:

请您帮我设置我的测试环境。 我在 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'

Selenium 我已经安装了

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

【问题讨论】:

    标签: php selenium testing webdriver phpunit


    【解决方案1】:

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

    在你的 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,但我添加了一些 moficiations):

        <?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 Standalone Server”并更改其名称并将其复制到 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(我们也可以将测试保存为原生 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
    

    享受:)

    【讨论】:

    • 一开始我对此投了反对票,因为你没有明确说明你在做什么,但它实际上看起来会起作用......话虽如此,这太脏了,无法尝试
    • 我希望,有更简单的解决方案,但这个工作,它是“全功能”(selenium IDE 记录测试支持(部分)+ 测试层次结构 + db clean + 屏幕截图在一个简单的命令'testrunner'):P
    【解决方案2】:

    你最近更新了你的 phpunit 吗?

    最新版本的phpunit不再用这个php绑定编译了,遇到了同样的问题。

    可以用phpunit-4.7.0版本测试吗?

    /usr/bin/wget https://phar.phpunit.de/phpunit-4.7.0.phar -O /vagrant/tools/phpunit.phar && chmod +x /vagrant/tools/phpunit.phar && sudo mv /vagrant/tools/phpunit.phar /usr/local/bin/phpunit
    

    搜索了我的 bash 历史记录并粘贴在那里,只需更正您的环境的路径即可。

    上面的行应该将您的 phpunit 更新为 4.7.0 版本,这是 phar 使用 PHPUnit_Extensions_Selenium2TestCase 绑定编译的版本。

    这应该可以,只要确保这个 phpunit 版本降级不会对您造成任何副作用。

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 2012-08-16
      • 1970-01-01
      • 2013-12-28
      • 2017-05-22
      • 2011-03-29
      • 2017-02-06
      • 2016-02-18
      • 2013-12-24
      相关资源
      最近更新 更多