文档
Welcome! 安装(Installation) 示例列表(List of examples) 依赖注入与服务定位器(Dependency Injection/Service Location) MVC 架构(The MVC Architecture) 使用控制器(Using Controllers) 使用模型(Working with Models) 模型元数据(Models Meta-Data) 事务管理(Model Transactions) Phalcon 查询语言(Phalcon Query Language (PHQL)) 缓存对象关系映射(Caching in the ORM) 对象文档映射 ODM (Object-Document Mapper) 使用视图(Using Views) 视图助手(View Helpers) 资源文件管理(Assets Management) Volt 模版引擎(Volt: Template Engine) MVC 应用(MVC Applications) 路由(Routing) 调度控制器(Dispatching Controllers) 微应用(Micro Applications) 使用命名空间(Working with Namespaces) 事件管理器(Events Manager) 请求环境 (Request Environment) 返回响应(Returning Responses) Cookie 管理(Cookies Management) 生成 URL 和 路径(Generating URLs and Paths) 闪存消息(Flashing Messages) 使用 Session 存储数据(Storing data in Session) 过滤与清理(Filtering and Sanitizing) 上下文编码(Contextual Escaping) 验证(Validation) 表单(Forms) 读取配置(Reading Configurations) 分页(Pagination) 使用缓存提高性能(Improving Performance with Cache) 安全(Security) 加密/解密( Encryption/Decryption ) 访问控制列表 ACL(Access Control Lists ACL) 多语言支持(Multi-lingual Support) 通用类加载器 ( Universal Class Loader ) 日志记录(Logging) 注释解析器(Annotations Parser) 命令行应用(Command Line Applications) 队列(Queueing) 数据库抽象层(Database Abstraction Layer) 国际化(Internationalization) 数据库迁移(Database Migrations) 调试应用程序(Debugging Applications) Phalcon 开发工具(Phalcon Developer Tools) 提高性能:下一步该做什么?(Increasing Performance: What's next?) 单元测试(Unit testing) 授权(License)
教程

发布于 2015-08-21 15:24:19 | 618 次阅读 | 评论: 0 | 来源: 网络整理

单元测试(Unit testing)

Writing proper tests can assist in writing better software. If you set up proper test cases you can eliminate most functional bugs and better maintain your software.

整合 PHPunit 到 phalcon(Integrating PHPunit with phalcon)

If you don’t already have phpunit installed, you can do it by using the following composer command:

composer require phpunit/phpunit

or by manually adding it to composer.json:

{
    "require-dev": {
        "phpunit/phpunit": "~4.5"
    }
}

Once phpunit is installed create a directory called ‘tests’ in your root directory:

app/
public/
tests/

Next, we need a ‘helper’ file to bootstrap the application for unit testing.

PHPunit 辅助文件(The PHPunit helper file)

A helper file is required to bootstrap the application for running the tests. We have prepared a sample file. Put the file in your tests/ directory as TestHelper.php.

<?php

use PhalconDI;
use PhalconDIFactoryDefault;

ini_set('display_errors',1);
error_reporting(E_ALL);

define('ROOT_PATH', __DIR__);
define('PATH_LIBRARY', __DIR__ . '/../app/library/');
define('PATH_SERVICES', __DIR__ . '/../app/services/');
define('PATH_RESOURCES', __DIR__ . '/../app/resources/');

set_include_path(
    ROOT_PATH . PATH_SEPARATOR . get_include_path()
);

// Required for phalcon/incubator
include __DIR__ . "/../vendor/autoload.php";

// Use the application autoloader to autoload the classes
// Autoload the dependencies found in composer
$loader = new PhalconLoader();

$loader->registerDirs(
    array(
        ROOT_PATH
    )
);

$loader->register();

$di = new FactoryDefault();
DI::reset();

// Add any needed services to the DI here

DI::setDefault($di);

Should you need to test any components from your own library, add them to the autoloader or use the autoloader from your main application.

To help you build the unit tests, we made a few abstract classes you can use to bootstrap the unit tests themselves. These files exist in the Phalcon incubator @ https://github.com/phalcon/incubator.

You can use the incubator library by adding it as a dependency:

composer require phalcon/incubator

or by manually adding it to composer.json:

{
    "require": {
        "phalcon/incubator": "dev-master"
    }
}

You can also clone the repository using the repo link above.

PHPunit.xml 文件(PHPunit.xml file)

Now, create a phpunit file:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./TestHelper.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         verbose="true"
         colors="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="true">
    <testsuite name="Phalcon - Testsuite">
        <directory>./</directory>
    </testsuite>
</phpunit>

Modify the phpunit.xml to fit your needs and save it in tests/.

This will run any tests under the tests/ directory.

简单的单元测试(Sample unit test)

To run any unit tests you need to define them. The autoloader will make sure the proper files are loaded so all you need to do is create the files and phpunit will run the tests for you.

This example does not contain a config file, most test cases however, do need one. You can add it to the DI to get the UnitTestCase file.

First create a base unit test called UnitTestCase.php in your /tests directory:

<?php

use PhalconDI;
use PhalconTestUnitTestCase as PhalconTestCase;

abstract class UnitTestCase extends PhalconTestCase
{
    /**
     * @var VoiceCache
     */
    protected $_cache;

    /**
     * @var PhalconConfig
     */
    protected $_config;

    /**
     * @var bool
     */
    private $_loaded = false;

    public function setUp(PhalconDiInterface $di = NULL, PhalconConfig $config = NULL)
    {
        // Load any additional services that might be required during testing
        $di = DI::getDefault();

        // Get any DI components here. If you have a config, be sure to pass it to the parent

        parent::setUp($di);

        $this->_loaded = true;
    }

    /**
     * Check if the test case is setup properly
     *
     * @throws PHPUnit_Framework_IncompleteTestError;
     */
    public function __destruct()
    {
        if (!$this->_loaded) {
            throw new PHPUnit_Framework_IncompleteTestError('Please run parent::setUp().');
        }
    }
}

It’s always a good idea to separate your Unit tests in namespaces. For this test we will create the namespace ‘Test’. So create a file called testsTestUnitTest.php:

<?php

namespace Test;

/**
 * Class UnitTest
 */
class UnitTest extends UnitTestCase
{
    public function testTestCase()
    {
        $this->assertEquals('works',
            'works',
            'This is OK'
        );

        $this->assertEquals('works',
            'works1',
            'This will fail'
        );
    }
}

Now when you execute ‘phpunit’ in your command-line from the tests directory you will get the following output:

$ phpunit
PHPUnit 3.7.23 by Sebastian Bergmann.

Configuration read from /private/var/www/tests/phpunit.xml

Time: 3 ms, Memory: 3.25Mb

There was 1 failure:

1) TestUnitTest::testTestCase
This will fail
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'works'
+'works1'

/private/var/www/tests/Test/UnitTest.php:25

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

Now you can start building your unit tests. You can view a good guide here (we also recommend reading the PHPunit documentation if you’re not familiar with PHPunit):

http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务