zoukankan      html  css  js  c++  java
  • PHPUnit 组织测试

    https://www.cnblogs.com/foreversun/p/6837147.html

    首先是目录结构

    源文件夹为 src/ 

    测试文件夹为 tests/

    User.php

    复制代码
    <?php
    class Errorcode
    {
        const NAME_IS_NULL = 0;
    }
    
    class User
    {
        public $name;
        public function __construct($name)
        {
            $this->name=$name;
        }
    
        public function Isempty()
        {
    
            try{
                if(empty($this->name))
                {
                    throw new Exception('its null',Errorcode::NAME_IS_NULL);
                }
            }catch(Exception $e){
                return $e->getMessage();
            }
    
            return 'welcome '.$this->name;
        }
    }
    复制代码

    对应的单元测试文件  UserTest.php

    复制代码
    <?php
    use PHPUnitFrameworkTestCase;
    
    class UserTest extends TestCase
    {
        protected $user;
        public function setUp()
        {
            $this->user = new User('');
        }
        public function testIsempty()
        {
            $this->user->name='mark';
            $result =$this->user->Isempty();
            $this->assertEquals('welcome mark',$result);
    
            $this->user->name='';
            $results =$this->user->Isempty();
            $this->assertEquals('its null',$results);
    
        }
    
    
    }
    复制代码

    第二个单元测试代码因为要引入 要测试的类  这里可以用 自动载入 避免文件多的话 太多include  

    所以在src/ 文件夹里写 autoload.php

    复制代码
    <?php
    
    function __autoload($class){
        include $class.'.php';
    }
    
    spl_autoload_register('__autoload');
    复制代码

    当需要User类时,就去include User.php。写完__autoload()函数之后要用spl_autoload_register()注册上。

    虽然可以自动载入,但是要执行的命令变得更长了。

    打开cmd命令如下

    1
    phpunit --bootstrap src/autoload.php tests/UserTest

    所以我们还可以在根目录写一个配置文件phpunit.xml来为项目指定bootstrap,这样就不用每次都写在命令里了。

    phpunit.xml

    <phpunit bootstrap="src/autoload.php">
    </phpunit>

    然后

    打开cmd命令 执行MoneyTest 命令如下

    1
    phpunit tests/UserTest

    打开cmd命令 执行tests下面所有的文件 命令如下  

    1
    phpunit tests

      

  • 相关阅读:
    Spring Security 3.2.x与Spring 4.0.x的Maven依赖管理
    文件下载-SpringMVC中測试
    Redhat 6.3中syslog信息丢失
    HDU2586 How far away ?(LCA模板题)
    android开机启动应用和服务
    swift 3.0基本数据语法
    swift 获取UI上某点点颜色
    Hello_IOS ios开发transform属性
    CGAffineTransformMakeTranslation和CGAffineTransform
    iOS 原生地图(MapKit、MKMapView)轨迹渐变
  • 原文地址:https://www.cnblogs.com/rxbook/p/9360717.html
Copyright © 2011-2022 走看看