Home  >  Article  >  Backend Development  >  How to use Behat in PHP programming?

How to use Behat in PHP programming?

WBOY
WBOYOriginal
2023-06-12 08:39:451398browse

In PHP programming, Behat is a very useful tool, which can help programmers better understand business requirements during the development process and ensure the quality of the code. In this article, we will introduce how to use Behat in PHP programming.

1. What is Behat?

Behat is a behavior-driven development (BDD) framework that couples PHP code through language description (use cases written in Gherkin language), thereby enabling code and business requirements to work together. Using Behat for testing allows programmers to transform from simple grammar and behavior verification to using natural language to express business instances and automatically verify these instances. Behat perfectly connects the description requirements of the "client" and the implementation processing of the "server".

2. Behat installation

Use composer (PHP package manager) to install Behat. Open the console (terminal) in the project directory and enter the following command:

composer require --dev behat/behat

Reminder: --dev indicates that Behat is used in development. If you are using Behat in a production environment, you should not add the --dev parameter.

3. Write Feature

After completing the installation, we can create Feature in the APP_PATH/features/ directory:

Feature: 搜索
  我想在“首页”上搜索某个商品
  为了快捷找到我需要的商品
  我需要查询到相应结果

  Scenario: 搜索结果是正确的
    Given 我在“首页”页面
    When 我输入“水杯”作为搜索关键字
    And 我点击“搜索”按钮
    Then 我应该看到网页标题包含“水杯”

The above Gherkin language describes a Feature, which contains A set of scenarios (Scenario) that describes how to complete a search and verify the results.

4. Configuring Behat

We need to define the configuration options of Behat through the configuration file config/behat.yml. The following is a simple configuration file:

default:
  suites:
    default:
      contexts:
        - FeatureContext
      filters:
        tags: ''
  extensions:
    BehatMinkExtension:
      base_url: "http://localhost/"
      files_path: "%paths.base%/persistent/files"
      goutte: ~
      selenium2: ~
    BehatSymfony2Extension:
      kernel:
        env: test
        debug: true

This configuration file tells Behat which Context class needs to be used and what kind of browser needs to be used.

5. Write the Context class

We need to create a Context class to process the steps defined in the Feature, and call the written test code to verify the correctness of the code. Codeception and PHPUnit are some testing libraries that support Behat. We will use PHPUnit to demonstrate how to write the Context class.

Create FeatureContext.php in the APP_PATH/features/bootstrap/ directory and add the following code:

<?php

use BehatBehatContextContext;
use BehatBehatHookScopeBeforeFeatureScope;
use BehatBehatTesterExceptionPendingException;
use BehatMinkWebAssert;
use BehatMinkExtensionContextMinkContext;
use PHPUnitFrameworkAssert as PHPUnit;

class FeatureContext extends MinkContext implements Context
{
 
    public function __construct($baseUrl)
    {
        $this->baseUrl = $baseUrl;
    }
 
    /**
     * @param BeforeFeatureScope $scope
     */
    public static function setup(BeforeFeatureScope $scope)
    {
        // 配置数据库等其他代码
    }

    /**
     * @Given /^我在“(.*)”页面$/
     */
    public function 在页面($page)
    {
        $this->visitPath(sprintf('/%s', $page));
    }

    /**
     * @When /^我输入“(.*)”作为搜索关键字$/
     */
    public function 输入作为搜索关键字($keyword)
    {
        $page = $this->getPage();
        $searchForm = $page->find('css', 'form[action="/search"]');
        $searchInput = $searchForm->find('css', 'input[type="text"]');
        $searchInput->setValue($keyword);
    }

    /**
     * @When /^我点击“(.*)”按钮$/
     */
    public function 点击按钮($button)
    {
        $page = $this->getPage();
        $button = $page->find('css', sprintf('input[type="submit"][value="%s"]', $button));
        $button->click();
    }

    /**
     * @Then /^我应该看到网页标题包含“(.*?)”$/
     */
    public function 应该看到网页标题包含($expected)
    {
        PHPUnit::assertTrue(stripos($this->getSession()->getPage()->getTitle(), $expected) !== false);
    }
}

The above code defines a set of steps (steps) for the scenario defined in Feature ( scenario) were implemented.

6. Execute the test

Execute the following command in the console:

vendor/bin/behat

After executing the command, Behat will be based on config/behat The configuration in the .yml file is executed on the Feature file. The console may have some progress bars and error prompts, and finally the test pass or failure information will be listed.

Here, we have learned how to use Behat in PHP programming to complete testing. Using Behat can improve the expressiveness of business code, reduce quality issues during the development process, and enhance team development collaboration and overall advancement efficiency.

The above is the detailed content of How to use Behat in PHP programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn