Unit testing and code coverage using PHP and PHPUnit

PHPz
Release: 2023-06-25 13:14:01
Original
1244 people have browsed it

With the development of software development, more and more developers are aware of the importance of unit testing. Unit testing is a common testing method in software development that ensures the correctness and stability of the code by testing the correctness of a single functional module (also called a "unit"). In this article, we will cover how to achieve unit testing and code coverage using PHP and PHPUnit.

PHPUnit is an open source testing framework for testing PHP code. It supports multiple test types including unit tests, functional tests, and integration tests. In this article, we will focus on unit testing.

Why unit testing and code coverage?

When developing software, we usually try to test our code as much as possible. Unit testing is a more efficient testing method that can continuously test during the development process to ensure the correctness of the code. In addition, it has the following benefits:

  1. Improve code maintainability: Through unit testing, you can quickly check the correctness of the code after modifying it to ensure that the original code is not damaged after the modification. function.
  2. Improve the robustness of the code: By testing each unit, potential problems and errors in the code can be discovered, so that these problems can be dealt with in advance to avoid causing problems in the production environment.
  3. Reduce the cost of scaling and refactoring: Unit testing can help you quickly find problems when modifying existing code, thereby managing changes in the code base more effectively.

Code coverage is a way to evaluate test coverage. It tells you how well your code has been tested. For example, if your test coverage is 60%, it means that your test code covers 60% of the source code. With code coverage, you can measure whether your software is of high quality and whether you need more test cases.

Start unit testing with PHPUnit

Before continuing, you need to make sure you have PHPUnit installed. Can be installed via Composer. Create a composer.json file in your project directory and add the PHPUnit dependency:

{
  "require-dev": {
    "phpunit/phpunit": "^7.0"
  }
}
Copy after login

Run the following command to install PHPUnit:

composer install --dev
Copy after login

Next, we will demonstrate how to write a simple unit tests. Imagine that you are writing a PHP class called "Calculator" that performs basic arithmetic operations. Here is its code:

class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }

    public function subtract($a, $b) {
        return $a - $b;
    }
}
Copy after login

Now, write a test class called "CalculatorTest" which will test our Calculator class:

use PHPUnitFrameworkTestCase;

class CalculatorTest extends TestCase {
    public function testAdd() {
        $calculator = new Calculator();
        $result = $calculator->add(1, 2);
        $this->assertEquals(3, $result);
    }

    public function testSubtract() {
        $calculator = new Calculator();
        $result = $calculator->subtract(2, 1);
        $this->assertEquals(1, $result);
    }
}
Copy after login

In the above code, we have used PHPUnit One of the basic test methods provided - assertEquals(). It compares the test value with the expected value and throws an exception if they are not equal.

Now run the PHPUnit test:

./vendor/bin/phpunit CalculatorTest.php
Copy after login

If all tests pass, the following output will be displayed:

PHPUnit 7.5.1 by Sebastian Bergmann and contributors.

..

Time: 42 ms, Memory: 4.00 MB

OK (2 tests, 2 assertions)
Copy after login

Note that a little trick is used in this example, which is The Calculator class and its corresponding test class CalculatorTest are both defined in the same file CalculatorTest.php.

Understand the basic testing methods of PHPUnit

PHPUnit provides a variety of testing methods. The following are usage examples of some of the basic methods:

  1. assertEquals($expected, $actual, $message): Compare the expected value and the actual value for equality.
  2. assertTrue($value, $message): Determine whether an expression is true.
  3. assertFalse($value, $message): Determine whether an expression is false.
  4. assertNull($value, $message): Determine whether a value is null.
  5. assertSame($expected, $actual, $message): Compares the expected value and the actual value for complete equality (including type).
  6. assertInstanceOf($expected, $actual, $message): Determine whether an object is an instance of a specific class.

More testing methods for PHPUnit can be found in the documentation.

Code coverage testing using PHPUnit

We have learned how to use PHPUnit for unit testing. Now, let us understand how to use PHPUnit for code coverage testing.

In order to achieve code coverage, we need to add the --coverage-html option when running PHPUnit. It will generate an HTML code coverage report. Just run the following command:

./vendor/bin/phpunit --coverage-html reports tests
Copy after login

This command runs all test cases in the test directory of our project and generates a code coverage report in the reports directory after running.

After this, you can open the HTML report in your browser to see the source code coverage.

Summary

In this article, we introduced how to use PHPUnit for unit testing and code coverage. With unit testing and code coverage, you can enhance project quality and stability and reduce the cost of scaling and refactoring.

When you write PHP code, remember to write good unit tests. A good unit test is used to verify code correctness, prevent regression errors, and ensure code robustness. By writing good test cases, you can catch problems early and fix them before they happen.

The above is the detailed content of Unit testing and code coverage using PHP and PHPUnit. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!