簡體   English   中英

使用PHPUnit和Selenium設置測試

[英]Set up tests with PHPUnit and Selenium

你能幫我設置我的測試環境嗎? 我在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

你能幫我繼續嗎? 謝謝 :)

以下是如何在phpUnit,MacOS,laravel 5.2,firefox上運行在Firefox上記錄的Selenium IDE測試的說明。 我還展示了如何在此處設置屏幕截圖(我還設置了Laravel以便在測試結束后能夠訪問DB以進行清理):

在test-s目錄中,創建selenium目錄。 並創建文件:SeleniumClearTestCase.php

class SeleniumClearTestCase extends MigrationToSelenium2 // Poniewaz testy seleniumIDE są zapisane w starym formacie (selenium 1) to urzywamy tej przejsciowki.
{
    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);
    }

    /**
     * Wykonaj screenshot w danym mommencie.
     * @return
     */
    public function screenshot()
    {
        $this->listener->addError($this, new Exception, null); // ta funkcja troche myli nazwą, ale wykona ona tylko screenshota nic ponadto
    }

    /**
     * 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)
     * Funkcja wykonuje kod js i jest uzywana w testach selenium IDE np. w funkcji 'storeEval'.
     * @param  string $javascriptCode Kod w JS np. "storedVars['registerurl'].match(/[^\\/]+$/)"
     * @param  [type] $args           tablica asocjacyjna klucz wartość z wartościami
     *                                jakie mają się znaleźć w zmiennej storedVars. np.
     *                                $args=['registerurl'=>'http://example.com']
     * @return string or array        jeżeli rezultat JS to string/liczba to zwraca je jak są
     *                                              jeżeli rezultat JS to tablica, to zwraca tablicę.
     */
    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安裝newerst 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

好的,現在我們有了setUp selenium和phpunit的所有文件。 所以讓我們在firefox中使用插件Selenium IDE進行一些測試,我們還需要安裝'Selenium IDE:PHP Formatters'插件,以便將測試保存為phpunit。 當我們記錄測試時,我們檢查它是否有效,我們將其保存為phpunit(我們也可以保存測試本機的html selenium格式.se - 擁有我們的php測試的'source',並且將來能夠運行它在selenium IDE中手工制作未來......) - 然后我們將其復制到文件夾測試/ 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功能中。 以下更復雜的測試使用靜態函數(也可以清理DB):

<?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

請享用 :)

你最近更新了你的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版本,這是一個使用PHPUnit_Extensions_Selenium2TestCase綁定編譯phar的版本。

這應該工作,只要確保這個phpunit版本降級不會對你造成任何副作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM