我变得悲伤
我使用 Laravel 5.2 并且正在开发我的单元测试。
在 Laravel 5.1 中,你可以使用很棒的 Integrated lib 来使用 selenium,但它在 Laravel 5.2 中似乎不起作用
那么基本上,L5.2 和 Selenium 之间是否有任何类型的集成,或者是不可能很好地使用它?
在这种情况下,我绝对应该留在 L5.1,因为测试是我的应用程序的基本部分:(
您需要使用composer安装PHPUnit_selenium包
composer require --dev phpunit/phpunit-selenium
在 laravel/tests/ 中创建 Selenium 测试用例类
<?php
class SeleniumTestCase extends PHPUnit_Extensions_Selenium2TestCase
{
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://localhost:8000/');
}
protected function visit($path)
{
$this->url($path);
return $this;
}
protected function see($text, $tag = 'body')
{
print_r(request()->session()->all());
//method call by tag name;
$this->assertContains($text,$this->byTag($tag)->text());
return $this;
}
protected function pressByName($text){
$this->byName($text)->click();
return $this;
}
protected function pressByTag(){
$this->byTag('button')->click();
return $this;
}
protected function type($value, $name)
{
$this->byName($name)->value($value);
return $this;
}
protected function hold($seconds){
sleep($seconds);
return $this;
}
}
并创建新的测试用例来访问主页网址
<?php
class ExampleTest extends SeleniumTestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testTitle()
{
$this->visit('/')
->see('Site title','title');
}
}
并从终端运行命令 PHPunit test
java -jar /usr/local/bin/selenium-server-standalone-2.35.0.jar
参考文档:
在 Laravel 5.2 及更高版本中,Laravel 团队引入了专门用于使用 Selenium 进行浏览器测试的 Laravel Dusk 包。 Dusk 提供了一个富有表现力、流畅的界面,用于使用浏览器自动化与您的应用程序进行交互。
要在 Laravel 5.2 中使用 Dusk 进行 Selenium 测试,可以按照以下步骤操作:
composer require --dev laravel/dusk
php artisan dusk:install
在你的
tests/DuskTestCase.php
:
<?php
namespace Tests;
use Laravel\Dusk\TestCase as BaseTestCase;
use Facebook\WebDriver\Chrome\ChromeOptions;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
// Add any additional options here
]);
return \Dusk\Chrome\ChromeDriver::create(
'http://localhost:9515', null, $options
);
}
}
您现在可以在tests/Browser目录中创建Dusk测试。例如:
<?php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class ExampleTest extends DuskTestCase
{
public function testBasicExample()
{
$this->browse(function (Browser $browser) {
$browser->visit('/')
->assertSee('Laravel');
});
}
}
运行时使用:
php artisan dusk