Home Backend Development PHP Tutorial How to use Behat in PHP programming?

How to use Behat in PHP programming?

Jun 12, 2023 am 08:39 AM
php language behat framework Programming test

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 我应该看到网页标题包含“水杯”
Copy after login

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
Copy after login

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);
    }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to deal with request header errors in PHP language development? How to deal with request header errors in PHP language development? Jun 10, 2023 pm 05:24 PM

In PHP language development, request header errors are usually caused by some problems in HTTP requests. These issues may include invalid request headers, missing request bodies, and unrecognized encoding formats. Correctly handling these request header errors is the key to ensuring application stability and security. In this article, we will discuss some best practices for handling PHP request header errors to help you build more reliable and secure applications. Checking the request method The HTTP protocol specifies a set of available request methods (e.g. GET, POS

How to use PHP's Ctype extension? How to use PHP's Ctype extension? Jun 03, 2023 pm 10:40 PM

PHP is a very popular programming language that allows developers to create a wide variety of applications. However, sometimes when writing PHP code, we need to handle and validate characters. This is where PHP's Ctype extension comes in handy. This article will introduce how to use PHP's Ctype extension. What are Ctype extensions? The Ctype extension for PHP is a very useful tool that provides various functions to verify the character type in a string. These functions include isalnum, is

How to avoid path traversal vulnerability security issues in PHP language development How to avoid path traversal vulnerability security issues in PHP language development Jun 10, 2023 am 09:43 AM

With the development of Internet technology, more and more websites and applications are developed using PHP language. However, security issues also arise. One of the common security issues is path traversal vulnerabilities. In this article, we will explore how to avoid path traversal vulnerabilities in PHP language development to ensure application security. What is a path traversal vulnerability? Path traversal vulnerability (PathTraversal) is a common web vulnerability that allows an attacker to access the web server without authorization.

How to use Behat in PHP programming? How to use Behat in PHP programming? Jun 12, 2023 am 08:39 AM

In PHP programming, Behat is a very useful tool that 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. Use Behat to do

How to use Phpt for unit testing in PHP How to use Phpt for unit testing in PHP Jun 27, 2023 am 08:35 AM

In modern development, unit testing has become a necessary step. It can be used to ensure that your code behaves as expected and that bugs can be fixed at any time. In PHP development, Phpt is a very popular unit testing tool, which is very convenient to write and execute unit tests. In this article, we will explore how to use Phpt for unit testing. 1. What is PhptPhpt is a simple but powerful unit testing tool, which is part of PHP testing. Phpt test cases are a series of PHP source code snippets whose

The php language supports several comment styles The php language supports several comment styles Feb 15, 2022 pm 02:05 PM

PHP language supports 3 comment styles: 1. C++ style, using the "//" symbol and the syntax "//comment content"; 2. C language style, using the "/* */" symbol and the syntax "/* comment content*" /"; 3. Shell style (Perl style), using the "#" symbol and the syntax "#comment content".

Common errors and solutions when parsing JSON in PHP language development Common errors and solutions when parsing JSON in PHP language development Jun 10, 2023 pm 12:00 PM

In PHP language development, it is often necessary to parse JSON data for subsequent data processing and operations. However, when parsing JSON, it is easy to encounter various errors and problems. This article will introduce common errors and processing methods to help PHP developers better process JSON data. 1. JSON format error The most common error is that the JSON format is incorrect. JSON data must comply with the JSON specification, that is, the data must be a collection of key-value pairs, and use curly brackets ({}) and square brackets ([]) to contain the data.

How to implement smart contracts in PHP? How to implement smart contracts in PHP? May 12, 2023 am 08:09 AM

Smart Contract is an automated transaction program based on the blockchain that can automatically execute, verify and execute transactions. Smart contracts can reduce human interference in transactions and improve transaction security and efficiency. Smart contracts are implemented slightly differently in different blockchains. This article will introduce how to implement smart contracts in PHP. PHP is a widely used programming language, especially suitable for web development. PHP has a mature open source ecosystem and many reliable frameworks and libraries. exist

See all articles