在長久的工作經(jīng)歷中荤胁,測試大佬常會在你耳旁嘀咕開發(fā)要自測要自測偎血。但是實際上開發(fā)往往只會關(guān)心當(dāng)前負(fù)責(zé)的單元功能的正確與否胯府。繁雜的開發(fā)任務(wù)當(dāng)中,還要兼顧所有流程的功能運(yùn)轉(zhuǎn)可能就沒那個精力了败徊,或者說這本身就是測試的工作颓遏。在遠(yuǎn)古時代互聯(lián)網(wǎng)領(lǐng)域工作還沒細(xì)分到前端鸠删、后端怯屉、測試、UI的時候附较,所有一攬子活都只有一個人做吃粒,那就是程序員。
但是如何盡量保證程序返回結(jié)果是預(yù)期的拒课? 能否做到每次發(fā)布之前自動對程序測試看是否達(dá)到預(yù)期徐勃?
這個時候我們可以引入自動化測試事示。
自動化測試范圍
- UI測試
- 接口測試
- 單元測試
- 數(shù)據(jù)測試
其中UI測試和數(shù)據(jù)測試的自動化可能是最不容易做且效益最小的。這部分可能最好是人為的進(jìn)行測試效果最好僻肖。
在體驗了java 的junit之后特別覺得junit的強(qiáng)大,其實PHP也可以做肖爵。接下來我們來了解下PHP的測試框架codeception
安裝使用
install
composer require "codeception/codeception" --dev
setup
php vendor/bin/codecept bootstrap
該命令會初始化配置文件和目錄
輕量安裝
Use predefined installation templates for common use cases. Run them instead of bootstrap command.
bootstrap
會默認(rèn)初始化所有測試類型所需要的組件,有些你不會用到的類庫也會安裝臀脏。推薦使用輕量安裝所用能到的測試類型劝堪。
例如你只需要單元測試,則可以
php vendor/bin/codecept init unit
suite配置
初始化之后還要對測試類型進(jìn)行相應(yīng)的配置,在tests目錄下新建unit的配置
# unit.suite.yml
# Codeception Test Suite Configuration
#
# Suite for unit or integration tests.
actor: UnitTester
modules:
enabled:
- Asserts
- \Helper\Unit
step_decorators: ~
codeception單元測試
codeception的單元測試其實也是基于phpunit之上構(gòu)建的揉稚。phpunit的單元測試用例可以之前在codeception上執(zhí)行秒啦。
創(chuàng)建單元測試
php vendor/bin/codecept generate:test unit Example
執(zhí)行完會在tests/unit目錄里創(chuàng)建測試用例文件
class ExampleTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected function _before()
{
}
protected function _after()
{
}
// tests
public function testMe()
{
}
}
- all public methods with test prefix are tests
- _before method is executed before each test (like setUp in PHPUnit)
- _after method is executed after each test (like tearDown in PHPUnit)
運(yùn)行用例
php vendor/bin/codecept run unit ExampleTest
運(yùn)行所有單元測試用例
php vendor/bin/codecept run unit
class UserTest extends \Codeception\Test\Unit
{
public function testValidation()
{
$user = new User();
$user->setName(null);
$this->assertFalse($user->validate(['username']));
$user->setName('toolooooongnaaaaaaameeee');
$this->assertFalse($user->validate(['username']));
$user->setName('davert');
$this->assertTrue($user->validate(['username']));
}
}
結(jié)果
可以統(tǒng)計到所有文件的覆蓋率和用例測試結(jié)果。
結(jié)合git鉤子我們可以在每次分支提交時進(jìn)行自動的用例測試窃植,能一定程度上防止代碼更改了而沒測試產(chǎn)生非預(yù)期的問題帝蒿。
博客內(nèi)容遵循 署名-非商業(yè)性使用-相同方式共享 4.0 國際 (CC BY-NC-SA 4.0) 協(xié)議
本文永久鏈接是:https://visonforcoding.github.io/2020/07/01/PHP%E7%94%9F%E6%80%81%E4%B9%8B%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/