behat 튜토리얼
behat 시작하기
수색…
비고
이 섹션에서는 behat가 무엇인지, 왜 개발자가 그것을 사용하고 싶어하는지에 대한 개요를 제공합니다.
그것은 또한 behat 내의 모든 큰 주제를 언급하고 관련 주제에 링크해야합니다. 설명서는 새 버전이므로 관련 항목의 초기 버전을 만들어야 할 수도 있습니다.
사용자 스토리로서의 기능 테스트
기능 테스트는 사용자 스토리에 대한 테스트로 가장 잘 설명됩니다. 사용자가 일반적으로 다음 패턴을 따르기 전에 사용자 스토리를 처리 한 경우 :
As a [role], I want to [desire], so that [benefit/desired outcome]
다음 예제에서는이 사용자 스토리를 예제로 사용합니다.
As a Dungeon Master, I want to ensure harmony and mutual trust, so that
the party can work together as a team
PHP에서 기능 테스트를 위해 가장 널리 사용되는 테스트 프레임 워크는 Behat 과 PHPSpec 입니다.
Behat으로 시작하기
Behat은 사람이 읽을 수있는 형식 인 Gherkin 구문 을 제공합니다. 사용자 스토리를 쉽게 설명 할 수 있습니다.
Behat으로 시작하려면 Composer와 함께 설치 한 다음 테스트 파일을 초기화해야합니다.
$ composer require --dev behat/behat="^3.0.5"
$ ./vendor/bin/behat --init
+d features # place your *.feature files here
+d features/bootstrap # place your context classes here
+f features/bootstrap/FeatureContext.php # place your definitions, transformations and hooks here
기본적으로 테스트 파일은 features/
folder에두고 확장자는 .feature
입니다.
각 테스트 파일은 응용 프로그램의 특정 기능을 정의해야합니다. 기능은 일련의 시나리오로 분류되며 시나리오를 성공적으로 수행하기 위해 수행해야하는 일련의 단계가 포함됩니다. 각 시나리오는 전달할 기능을 전달해야합니다.
# features/PartyHarmony.feature
Feature: Party Harmony
As a Dungeon Master, I want to ensure harmony and mutual trust, so that
the party can work together as a team
Scenario: Teach members to respect each others property
Given that the Wizard has 10 cookies
And the Bard eats 1 cookie
Then the Bard is mysteriously on fire
테스트를 실행하려면 Behat 바이너리를 직접 실행해야합니다. 실행될 기능 파일을 선택적으로 지정할 수 있습니다 (그렇지 않으면 모든 테스트가 실행됩니다). 이 기능 파일은 정의되지 않은 단계 오류로 인해 실패합니다 (해당 단계의 의미를 정의하지 않았으므로).
$ ./vendor/bin/behat features/PartyHarmony.feature
Feature: Party Harmony
As a Dungeon Master, I want to ensure harmony and mutual trust, so that
the party can work together as a team
Scenario: Teach members to respect each others property # features/PartyHarmony.feature:6
Given that the Wizard has 10 cookies
And the Bard eats 1 cookie
Then the Bard is mysteriously on fire
1 scenario (1 undefined)
3 steps (3 undefined)
0m0.01s (10.49Mb)
--- FeatureContext has missing steps. Define them with these snippets:
/**
* @Given that the Wizard has :arg1 cookies
*/
public function thatTheWizardHasCookies($arg1)
{
throw new PendingException();
}
/**
* @Given the Bard eats :arg1 cookie
*/
public function theBardEatsCookie($arg1)
{
throw new PendingException();
}
/**
* @Then the Bard is mysteriously on fire
*/
public function theBardIsMysteriouslyOnFire()
{
throw new PendingException();
}
시나리오의 각 단계는 컨텍스트 PHP 파일에서 코드 조각을 실행합니다 (다른 기능 테스트는 다른 컨텍스트를로드 할 수 있음). Behat에서 제안한 예제를 복사하거나 자체 예제를 만들 수 있습니다. 단계는 정규식 검사와 일치합니다. 따라서 우리가
<?php
#
class FeatureContext {
/**
* @Given that the wizard has :num cookies
*/
public function wizardHasCookies($num) {
// $this->wizard is a pre-existing condition.... like syphilis
$this->wizard->setNumberOfCookies($num);
}
/**
* @Given the Bard eats :num cookie
*/
public function theBardEatsCookie($num)
{
$this->bard->consumeCookies($num);
}
/**
* @Then the Bard is mysteriously on fire
*/
public function theBardIsMysteriouslyOnFire() {
PHPUnit_Framework_Assert::assertTrue(
$this->bard->isBardOnFire()
);
}
}
PHPUnit_Framework_Assert
사용하게 PHPUnit_Framework_Assert
. Behat은 자신이 주장하는 시스템을 가지고 있지 않으므로 원하는 것을 사용할 수 있습니다.
이제 테스트를 실행하면 실제 코드가 실행되고 모든 것이 통과되는지 테스트 할 수 있습니다.
$ ./vendor/bin/behat features/PartyHarmony.feature
Feature: Party Harmony
As a Dungeon Master, I want to ensure harmony and mutual trust, so that
the party can work together as a team
Scenario: Teach members to respect each others property # features/PartyHarmony.feature:6
Given that the Wizard has 10 cookies # FeatureContext::thatTheWizardHasCookies()
And the Bard eats 1 cookie # FeatureContext::theBardEatsCookie()
Then the Bard is mysteriously on fire # FeatureContext::theBardIsMysteriouslyOnFire()
1 scenario (1 passed)
3 steps (3 passed)
0m0.01s (10.59Mb)
밍크와 함께 Behat 확장하기
Mink는 웹 드라이버 (Goutte 및 Selenium과 같은 인터페이스)와 확장 된 MinkContext
를 제공하여 단계별로 추가 웹 언어를 제공합니다.
Mink (및 기본 Goutte 드라이버)를 설치하려면 다음과 같이하십시오.
$ composer require --dev behat/mink-extension="^2.0"
$ composer require --dev behat/mink-goutte-driver="^1.0"
그런 다음 MinkContext
컨텍스트를 확장합니다.
<?php
use Behat\MinkExtension\Context\MinkContext;
class FeatureContext extends MinkContext … {
…
}
다음 명령을 사용하여 Behat 설치에서 사용할 수있는 전체 구문 목록을 볼 수 있습니다.
$ ./vendor/bin/behat -dl
Given /^(?:|I )am on "(?P<page>[^"]+)"$/
When /^(?:|I )reload the page$/
When /^(?:|I )move backward one page$/
When /^(?:|I )move forward one page$/
When /^(?:|I )press "(?P<button>(?:[^"]|\\")*)"$/
When /^(?:|I )follow "(?P<link>(?:[^"]|\\")*)"$/
When /^(?:|I )fill in "(?P<field>(?:[^"]|\\")*)" with "(?P<value>(?:[^"]|\\")*)"$/
그런 다음 테스트 할 웹 사이트의 위치와 사용할 웹 드라이버 (기본적으로 Goutte)를 나타내도록 Mink를 구성해야합니다.
# ./behat.yml
default:
extensions:
Behat\MinkExtension:
base_url: "[your website URL]"
sessions:
default:
goutte: ~
다음은 Mink에서 제공 한 단계만을 사용하는 시나리오의 예입니다.
# ./features/Authentication.feature
Feature: Authentication
As a security conscious developer I wish to ensure that only valid users can access our website.
Scenario: Login in successfully to my website
When I am on "/login"
And I fill in "email" with "[email protected]"
And I fill in "password" with "my_password"
And I press "Login"
Then I should see "Successfully logged in"
Scenario: Attempt to login with invalid credentials
When I am on "/login"
And I fill in "email" with "[email protected]"
And I fill in "password" with "not_my_password"
And I press "Login"
Then I should see "Login failed"
이제 Behat을 통해이 기능을 실행하여이를 테스트 할 수 있습니다.
./vendor/bin/behat features/Authentication.feature
일반적인 단계를 위해 MinkContext
를 사용하여 자신 만의 단계를 만들 수 있습니다 (예 : 로그인은 매우 일반적인 작업입니다).
Feature: Authentication
As a security conscious developer I wish to ensure that only valid users can access our website.
Scenario: Login in successfully to my website
Given I login as "[email protected]" with password "my_password"
Then I should see "Successfully logged in"
Scenario: Attempt to login with invalid credentials
Given I login as "[email protected]" with password "not_my_password"
Then I should see "Login failed"
웹 드라이버와 페이지 상호 작용에 액세스하려면 MinkContext
로 컨텍스트 파일을 확장해야합니다.
<?php
use Behat\MinkExtension\Context\MinkContext;
class FeatureContext extends MinkContext {
/**
* @Given I login as :username with password :password
*/
public function iLoginAsWithPassword($username, $password) {
$this->visit("/login");
$this->fillField("email", $username);
$this->fillField("password", $password);
$this->pressButton("Login");
}
}
Mink는 또한 다음과 같은 구문을 사용하여 페이지의 요소를 식별 할 수 있도록 미리 지정된 호출의 대부분에서 CSS 선택기를 제공합니다.
When I click on "div[id^='some-name']"
And I click on ".some-class:first"
And I click on "//html/body/table/thead/tr/th[first()]"
Mink와 Selenium으로 JavaScript 테스트하기
웹 사이트에서 JavaScript를 테스트하려면 Goutte (Guzzle을 통한 cURL)보다 조금 더 강력한 것을 사용해야합니다. ZombieJS , Selenium 및 Sahi 와 같은 몇 가지 옵션이 있습니다. 이 예제에서는 Selenium을 사용할 것이다.
먼저 Mink 용 드라이버를 설치해야합니다.
$ composer require --dev behat/mink-selenium2-driver="^1.2"
그리고 Selenium 독립형 서버 jar 파일을 다운로드하여 시작해야합니다.
$ java -jar selenium-server-standalone-2.*.jar
우리는 또한 우리가 사용할 때 Behat 이야기해야합니다 @javascript
셀레늄 드라이버를 사용하고 셀레늄 독립형 서버의 위치를 제공하는 태그를.
# ./behat.yml
default:
# …
extensions:
Behat\MinkExtension:
base_url: "[your website URL]"
sessions:
# …
javascript:
selenium2:
browser: "firefox"
wd_host: http://localhost:4444/wd/hub
그런 다음 브라우저 에뮬레이션을 사용하여 실행하려는 각 테스트마다 기능 또는 시나리오의 시작 부분에 @javascript
(또는 @selenium2
) 태그를 추가하기 @javascript
됩니다.
# ./features/TestSomeJavascriptThing.feature
@javascript # or we could use @selenium2
Feature: This test will be run with browser emulation
테스트는 Behat을 통해 실행될 수 있습니다 (다른 테스트와 마찬가지로). 한가지 차이점은 테스트가 실행될 때 Selenium 독립 실행 형 서버를 실행하는 컴퓨터에 브라우저 창을 생성하여 설명 된 테스트를 수행해야한다는 것입니다.
테스트 데이터 설정
기능 테스트에서 데이터는 종종 수정됩니다. 이로 인해 테스트 스위트의 후속 실행이 실패 할 수 있습니다 (데이터가 원래 상태에서 변경되었을 수 있음).
Doctrine , Propel , Laravel 과 같은 마이그레이션 또는 시드 (seeding)를 지원하는 ORM 또는 프레임 워크를 사용하여 데이터 소스를 설정 한 경우이를 사용하여 각 테스트 실행시 Fixture 데이터로 완료된 새 테스트 데이터베이스를 만들 수 있습니다.
현재 이들 중 하나 (또는 동등한 것) 중 하나를 사용하지 않는 경우 Phinx 와 같은 도구를 사용하여 새 테스트 데이터베이스를 신속하게 설정하거나 각 테스트 실행에 대해 기존 데이터베이스를 준비 할 수 있습니다 (테스트 항목 정리, 원래 상태로 다시 재설정). ).
# Install Phinx in your project
$ php composer.phar require robmorgan/phinx
$ php vendor/bin/phinx init
Phinx by Rob Morgan - https://phinx.org. version x.x.x
Created ./phinx.xml
./phinx.xml
데이터베이스 자격 증명을 추가하십시오.
$ php vendor/bin/phinx create InitialMigration
문서에 제공된 구.을 사용하여 데이터베이스 테이블이 작성되고 채워지는 f}을 지정할 수 있습니다.
그런 다음 테스트를 실행할 때마다 다음과 같은 스크립트를 실행합니다.
#!/usr/bin/env bash
# Define the test database you'll use
DATABASE="test-database"
# Clean up and re-create this database and its contents
mysql -e "DROP DATABASE IF EXISTS $DATABASE"
mysql -e "CREATE DATABASE $DATABASE"
vendor/bin/phinx migrate
# Start your application using the test database (passed as an environment variable)
# You can access the value with $_ENV['database']
database=$DATABASE php -d variables_order=EGPCS -S localhost:8080
# Run your functional tests
vendor/bin/behat
이제 데이터 변경으로 인해 기능 테스트가 실패하지 않아야합니다.
이메일 캡처
기능 테스트에는 외부 API 호출 및 전자 메일과 같이 환경을 벗어나는 프로세스 테스트도 포함될 수 있습니다.
예를 들어, 웹 사이트 등록 프로세스를 기능적으로 테스트하고 있다고 가정 해보십시오. 이 프로세스의 마지막 단계는 활성화 링크가 포함 된 이메일을 보내는 것입니다. 이 링크를 방문 할 때까지 계정이 완전히 등록되지 않았습니다. 둘 다 테스트 해보고 싶습니다.
- 이메일이 올바르게 전송되도록 (형식 지정, 자리 표시 자 교체 등)
- 활성화 링크 작동 여부
이제 이메일 전송을 테스트 할 수 있지만 IMAP 또는 POP 클라이언트를 사용하여 사서함에서 보낸 전자 메일을 검색 할 수는 있지만 인터넷 연결, 원격 전자 메일 서버 및 배달 중에 발생할 수있는 모든 문제 (스팸 탐지 예를 들어).
더 간단한 해결책은 보내는 SMTP 연결을 트랩하고 보낸 전자 메일을 디스크에 덤프하는 로컬 서비스를 사용하는 것입니다.
몇 가지 예가 있습니다 :
smtp-sink - Postfix에 번들로 제공되는 유틸리티 프로그램입니다.
# Stop the currently running service
sudo service postfix stop
# Dumps outgoing emails to file as "day.hour.minute.second"
smtp-sink -d "%d.%H.%M.%S" localhost:2500 1000
# Now send mails to your local SMTP server as normal and they will be
# dumped to raw text file for you to open and read
# Run your functional tests
vendor/bin/behat
smtp-sink
를 죽이고 나중에 postfix 서비스를 다시 시작하는 것을 잊지 마십시오.
# Restart postfix
sudo service postfix start
FakeSMTP - 보내는 메일을 트랩하는 Java 기반 클라이언트
# -b = Start without GUI interface
# -o = Which directory to dump your emails to
$ java -jar fakeSMTP.jar -b -o output_directory_name
또는 메일 트랩 과 같은 서비스를 제공하는 원격 서비스를 사용할 수 있지만 테스트는 인터넷 액세스에 달려 있습니다.
설치 또는 설정
보헤트 / 밍크
작곡가를 사용하여 설치하기 (다른 방법으로 확인하기) behat.org 리눅스를 사용하는 경우, php-curl을 설치했는지 확인하십시오 (정상적인 컬 설치가 작동하지 않습니다)
리눅스
sudo apt-get install php5-curl
Windows 를 사용하는 경우 PHP, Curl 및 Git이 설치되어 있는지 확인하십시오. 다음 링크에서 찾을 수 있습니다.
- PHP (Xampp) : https://www.apachefriends.org/de/index.html
- Curl : http://curl.haxx.se/latest.cgi?curl=win64-nossl
- 힘내 : http://git-scm.com/download/win
당신의 composer.json은 다음을 포함합니다 :
behat - 작곡가 .json
{
"require": {
"behat/behat": "dev-master",
"behat/mink": "dev-master",
"behat/mink-extension": "dev-master",
"behat/mink-selenium2-driver": "dev-master",
"phpunit/php-code-coverage": "dev-master",
"phpunit/phpunit-mock-objects": "dev-master",
"phpunit/phpunit": "dev-master"
},
"minimum-stability": "dev",
"config": {
"bin-dir": "bin/"
}
}
(Windows에서 composer.json 파일을 저장할 때 Filetype과 "ANSI"코딩으로 "모든 파일"을 선택해야합니다)
그 후에 다음 명령을 실행하십시오 :
$ curl http://getcomposer.org/installer | php
$ php composer.phar install
이 Behat, Mink 및 Behat-Mink 확장이 설치된 후, behat를 실행하려면
행동을 실행시키다.
$ bin/behat
Behat-Mink Extension을 활성화하려면 : behat.yml 다음 내용으로 "behat.yml"파일을 생성하십시오
behat.yml
default:
suites:
default:
paths:
features: %paths.base%/features/
bootstrap: %paths.base%/features/bootstrap/
contexts:
- FeatureContext
extensions:
Behat\MinkExtension:
base_url: 'http://www.startTestUrl.de'
selenium2:
browser: firefox
wd_host: "http://localhost:4444/wd/hub"
이 파일은 bin 디렉토리와 behat에 대한 링크가 들어있는 동일한 디렉토리에 있습니다.
또한 yml 파일에서 들여 쓰기에 탭을 사용하지 마십시오. 공백을 사용하십시오. behat-mink에서 사용할 수있는 명령 목록을 얻으려면 다음 명령을 사용하십시오.
$ bin/behat -di
시스템의 일부분을 만드십시오.
리눅스
Homedirectory로 이동하여 다음을 수행하십시오.
$ sudo vi .bashrc
그리고이 줄을 디렉터리의 끝에 추가하십시오.
export BEHAT_HOME=/home/*user*/path/to/behat
export PATH=$BEHAT_HOME/bin:$PATH
콘솔을 다시 시작하거나 "source .bashrc"를 입력하십시오.
Windows
Systemsettings를 실행하고 환경 변수에 behat / bin의 경로를 추가하십시오.
다른 드라이버 Selenium, phantomjs, goutte 등과 같은 드라이버는 반드시 설치해야합니다.