phpunit 入門

來源:互聯網
上載者:User

標籤:目的   查看   attr   extend   設定   tee   install   pos   log   

話說,使用phpunit還是處於好奇之心,為什麼以前一直沒使用呢?主要是嫌麻煩,小項目,前後端都是自己寫,幾個人就完成的工作,沒必要弄的那麼麻煩。好了,廢話不多說,讓我們一起來感受下phpunit吧!

假設,我們有一個項目Demo,Demo是使用Composer做的依賴管理。那麼我們只需要以下幾步就可完成phpunit的安裝和使用:

一、phpunit安裝:

  1、下載phpunit:wget https://phar.phpunit.de/phpunit.phar

  2、修改下載檔案的許可權:chmod +x phpunit.phar

  3、將phpunit設定為全域變數:mv phpunit.phar /usr/local/bin/phpunit

  4、查看phpunit版本:phpunit -V

二、項目Demo中引入phpunit組件:

  1、開啟composer.json檔案,添加"require-dev": {"phpunit/phpunit": "5.7.*"},然後composer install (等同於 composer require "phpunit/phpunit:5.7.*")

  2、執行完步驟1以後,phpunit組件將會存在於vendor/phpunit/phpunit

  3、phpunit的檔案目錄:

├── phpunit.xml├── src│   ├── autoload.php│   └── PhpUnitClass.php└── tests    └── PhpUnitClassTest.php

  4、phpunit.xml 為核心設定檔,暫不介紹,預設即可

  5、src中存放真實的服務類,當然一般我們都會把項目的服務類放到其他目錄

  6、tests存放所有的測試類別,所有測試類別必須繼承PHPUnit\Framework\TestCase;所有測試類別命名最好為*Test.php;測試類別中的所有方法必須為test*

  7、一個簡單的phpunit例子:

  服務類,PhpUnitClass:

namespace AppService;class PhpUnitClass{    private $att;    public function __construct($at)    {        echo "phpunitclass init";        $this->att=$at;    }    public function say(){        return "say";    }}

  單元測試類,PhpUnitClassTest:

class PhpUnitClassTest extends \PHPUnit\Framework\TestCase{    public function testPhpUnitClassInit(){        $unit=new \AppService\PhpUnitClass("init");        $this->assertAttributeEquals("init","att",$unit);    }    public function testPhpUnitClassSay(){        $unit=new \AppService\PhpUnitClass("init");        $this->assertEquals("say",$unit->say());    }}

  8、cd進入目錄tests,在終端執行:phpunit PhpUnitClassTest 即可執行單元測試

以上,便是一個phpunit簡單的入門總結,方便以後查閱。

laravel項目內建phpunit,所有的測試類別在根目錄tests/ 下存放。

phpunit 入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.