莫菲    

laravel phpunit 的使用

8年前发布  · 1223 次阅读
  laravel5  phpunit 

1.打开命令提示符执行: 

composer dump-autoload --optimize 


2.使用命令提示符进入laravel项目目录,例如我的项目名字为billing: 
该项目目录下有一个tests文件夹,里面存放单元测试文件(默认有一个ExampleTest.php): 
在该项目目录下,执行: 

phpunit tests/ExampleTest.php


简单测试例子: 

<?php
class PayonlineTest extends TestCase {
    /**
     * 测试Payonline接口请求
     * @author weilj
     * @param $r_arr 生成的随机请求元素数组
     */
    public function testElement()
    {
        $pay_id=['alipay','ipay','chinabank','99bill','99billrmb','yeepay'];
        $user_a=['1000','16455','16456','16457','16458','16459','16460','16473','16474'];
        $in=rand(0, count($pay_id)-1);
        $r_order=rand(20000101,20160420);
        $r_user=rand(0, count($user_a)-1);
        $sTime=rand(strtotime('2000-01-01 16:00:10'),strtotime("2010-01-01 23:59:59"));
        $eTime=rand(strtotime('2010-01-02 00:00:00'),strtotime("now"));
        $elements=['UserId'=>$user_a[$r_user],
            'OrderId'=>strval($r_order),
            'State'=>rand(1,4),
            'Money_s'=>rand(1,4999),
            'Money_e'=>rand(5000,9999),
            'Platform'=>$pay_id[$in],
            'STime'=>$sTime,
            'ETime'=>$eTime+1000,
            'Page'=>rand(1,10),
            'PageSize'=>rand(1,100)];
        $eCount=count($elements);
        $i=rand(0,$eCount-1);
        $r_arr=array_slice($elements,$i);
        $response = $this->call('GET', 'Payonline',$r_arr);
        $this->assertEquals(200, $response->status());
        $this->assertResponseOk();
        $output= json_decode($this->call('GET', 'Payonline',$r_arr)->getContent());
        $this->seeJsonStructure(['RequestId']);
        if(!empty($output->Data))
        {
            $this->seeJsonStructure([
                'Data'=>[
                    'TotalCount',
                    'List'=>[
                        '*' => [
                            'OrderId','Platform','Money','CreateTime','UserId','State'
                        ]
                    ]
                ]
            ]);
        }
    }
}


验证输出的json格式如下: 

{
    "RequestId": "******",
    "Data": {
        "TotalCount": 2472,
        "List": [
            {
                "FinanceId": ****,
                "STime": 1461483709,
                "ETime": 1461402274,
                "PType": 1,
                "RegionId": 1,
                "Balance": *****,
                "Money": "*****",
                "Detail": {
                    "StorageSize": ***,
                    "StorageMoney": ****,
                    "ThroughPutSize": ***,
                    "ThroughPutMoney": ***,
                    "ApiCountSize": null,
                    "ApiCountMoney": null
                }
            }
        ]
    }
}