Home php教程 php手册 PHP单元测试利器 PHPUNIT深入用法(三)第1/2页

PHP单元测试利器 PHPUNIT深入用法(三)第1/2页

Jun 21, 2016 am 08:55 AM
function phpunit public

在本文中,笔者将为大家介绍phpunit中的两个高级概念和用法,尽管它不一定在你的日常单元测试中都用到,但理解和学会它们的用法对学习phpunit还是十分重要的。

  Phpunit中的Annotations

  如果有其他编程语言经验的开发者,应该对Annotations(注解)不陌生,其实在phpunit中,一个简单的如下面的一段注释也可以认为是Annotations:

php
class MyTestClass extends PHPUnit_Framework_TestCase
{
/**
* Testing the answer to “do you love unit tests?”
*/
public function testDoYouLoveUnitTests()
{
$love = true;
$this->assertTrue($love);
}
}
?>

  可以看到,其实一段以/** **/为标记的文字,就可以认为是一种Annotations,但Annotations其实不单单是简单的注释,它是与一个程序元素相关联信息或者元数据的标注,它不影响程序的运行,但相关的软件工具或框架能够将其转换成特殊的元数据标记,以方便开发者以更少的代码去提高效率(比如通过。如果你熟悉Java,则会发现在Java SE 5中及象Spring等框架中,都大量使用了Annotations。

  然而,由于php并不象Java那样是编译性语言,因此本身缺乏去解析Annotations的机制,但幸好phpunit去提供了这样的功能,我们以下面的代码为例:

php
class MyMathClass
{
/**
* Add two given values together and return sum
*/
public function addValues($a,$b)
{
return $a+$b;
}
}
?>

  上面的只是一个简单的加法的例子,为此,我们使用Annotations去编写一个单元测试,在上两篇文章中,我们采用的是手工编写单元测试的方法,而本文中,将介绍使用phpunit命令行的方法,自动生成单元测试的框架,方法如下:

  首先把上面的类保存为MyMathClass.php,然后在命令行下运行如下命令:

phpunit –skeleton-test MyMathClass

  这时phpunit会自动生成如下的框架单元测试代码:

php
require_once "/path/to/MyMathClass.php";
/**
* Test class for MyMathClass.
* Generated by PHPUnit on 2011-02-07 at 12:22:07.
*/
class MyMathClassTest extends PHPUnit_Framework_TestCase
{
/**
* @var MyMathClass
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = new MyMathClass;
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @todo Implement testAddValues().
*/
public function testAddValues()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
"This test has not been implemented yet."
);
}
}
?>

  可以看到,phpunit为我们生成的单元测试代码自动引入了原来的MyMathClass.php,同时也生成了setUp和tearDown方法,但唯一的核心单元测试代码是留给了我们编写。如果想在这个基础上更快速的生成我们想要的单元测试代码,要如何实现呢?没错,就是使用annotations!我们可以在原来的MyMathClass.php中加入如下的annotations。

php
class MyMathClass
{
/**
* Add two given values together and return sum
* @assert (1,2) == 3
*/
public function addValues($a,$b)
{
return $a+$b;
}
}
?>

  然后再象上述一样在命令行运行:

phpunit –skeleton-test MyMathClass

  这个时候会为我们生成如下的单元测试代码:

php
/**
* Generated from @assert (1,2) == 3.
*/
public function testAddValues()
{
$this->assertEquals(
3,
$this->object->addValues(1,2)
);
}
?>

  看到了么?我们在原有的类中加入了注解@assert(1,2)==3,则phpunit自动为我们生成了正确的单元测试代码。当然,可以参考phpunit手册,学习到更多的关于@assert注解使用的规则。

  下面再举一个例子来讲解annotations。假设我们的程序中的一个方法,只是仅需要数据的输入,并且不依赖XML或者数据库提供数据源,则为了测试这个方法,我们可能想到的一个方法是在程序中设置一个测试数据集去测试,但这里介绍一个比较简单的方法,就是使用注解@dataProvider,修改MyMathClass.php如下:

php
/**
* Data provider for test methods below
*/
public static function provider()
{
return array(
array(1,2,3),
array(4,2,6),
array(1,5,7)
);
}
/**
* Testing addValues returns sum of two values
* @dataProvider provider
*/
public function testAddValues($a,$b,$sum)
{
$this->assertEquals(
$sum,
$this->object->addValues($a,$b)
);
}
?>

  可以看到,这里使用了注解@dataProvider,指明了测试用例的数据提供者是由provider方法返回的一个数组。所以在单元测试时,数组中的第0个元素则会赋值给$a,第1个元素则会赋值给b,第3个元素则会赋值给sum,可以看到,上面的第3个数组提供的数据是不能通过单元测试的,因为1+5不等于7。

  此外,这里还简单介绍两个常用的annotations,比如@expectedException注解可以测试代码中是否正确抛出了异常,比如:

phprequire_once "PHPUnit/Framework.php";
class ExceptionTest extends PHPUnit_Framework_TestCase{
/**
* @expectedException InvalidArgumentException
*/
public function testException() {
}
}

?>

  这里就用注解的方法表示testException中必须抛出的异常类型为InvalidArgumentException。

  另外一个是@cover注解。它的作用是标识phpunit只为类中的哪些方法或作用域生成测试代码,比如:

/**
* @covers SampleClass::publicMethod
* @covers SampleClass::
* @covers HelperClass
*/
public function testMethod()
{
$result = SampleClass::method();
}

  则phpunit只为SampleClass类中的publicMethod方法、SampleClass类中的所有非public声明的方法和HelperClass类或者它的其中一个父类产生单元测试代码。



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

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 use PHPUnit for Mock testing in PHP development How to use PHPUnit for Mock testing in PHP development Jun 27, 2023 am 10:25 AM

In PHP development, testing is a very important link. Testing can greatly reduce the occurrence of errors and improve code quality. Mock testing is a form of testing that can simulate fake objects or data in order to test a specific function or scenario of our code. PHPUnit is a very popular testing framework in PHP, which supports Mock testing. In this article, we will explore how to use PHPUnit for mock testing. 1. What is Mock testing? Before we start, let’s come first

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Test reporting tool in PHP Test reporting tool in PHP May 24, 2023 am 08:24 AM

PHP is a common open source programming language that is widely used in Web development. Its advantages are that it is easy to learn, easy to use, and highly scalable. As developers, in order to improve development efficiency while ensuring code quality, it is essential to use testing and test reports. In PHP development, there are many testing and test reporting tools, the most common of which is PHPUnit. However, although PHPUnit is simple and easy to use, it requires some basic knowledge of writing test cases. If you are not familiar with it, it is still difficult to use it.

What is the difference between the developer version and the public version of iOS? What is the difference between the developer version and the public version of iOS? Mar 01, 2024 pm 12:55 PM

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

Code inspection tools in PHP Code inspection tools in PHP May 24, 2023 pm 12:01 PM

Checking code quality is a task that every programmer must do, and there are many tools in PHP that can be used to check the quality and style of code, thereby improving the readability and maintainability of the code, and improving the reliability and security of the code. sex. This article will introduce several common PHP code inspection tools and conduct a simple comparison and evaluation of them. I hope it can help readers choose appropriate tools during the development process and improve code quality and efficiency. PHP_CodeSnifferPHP_CodeSniffer is a widely used

How to use PHPUnit and Mockery for unit testing? How to use PHPUnit and Mockery for unit testing? May 31, 2023 pm 04:10 PM

In PHP project development, unit testing is a very important task. PHPUnit and Mockery are two very popular PHP unit testing frameworks. PHPUnit is a widely used unit testing tool, while Mockery is an object simulation tool that focuses on providing a unified and concise API to create and manage object mocks. By using PHPUnit and Mockery, developers can quickly and efficiently perform unit testing to ensure the correctness and stability of their code base

What are the common code quality tools in PHP programming? What are the common code quality tools in PHP programming? Jun 12, 2023 am 08:16 AM

What are the common code quality tools in PHP programming? In modern software development, code quality is very important. If the code quality is not good, it will not only reduce the readability of the code and increase the difficulty of maintenance, but also cause a series of problems such as security vulnerabilities. In PHP programming, we can use some code quality tools to check the quality of the code. This article will introduce some common PHP code quality tools. PHP_CodeSnifferPHP_CodeSniffer is a tool for static analysis of PHP code

How to check code convention and quality using PHP and PHPUnit How to check code convention and quality using PHP and PHPUnit Jun 25, 2023 pm 04:57 PM

In modern software development, code quality and specifications are extremely important factors. Not only can it make the code cleaner and easier to maintain, it can also improve the readability and scalability of the code. But how do you check the quality and specification of your code? This article will explain how to use PHP and PHPUnit to achieve this goal. Step 1: Check the code specification. In PHP development, there is a very popular code specification, which is called PSR (PHP Standard Specification). The purpose of the PSR specification is to make PHP code more readable and maintainable. in

See all articles