php unit. y. muzychushun
TRANSCRIPT
Модульне тестування і
PhpUnit
Модульне тестування ...?
Модульне тестування, або юніт-тестування (англ. unit testing) - процес у програмуванні, що дозволяє перевірити на коректність окремі модулі вихідного коду програми.
Ідея полягає в тому, щоб писати тести для кожної функції або методу. Це дозволяє досить швидко перевірити, чи не призвела чергове зміна коду до до появи помилок у вже відтестованих місцях програми, а також полегшує виявлення та усунення таких помилок.
Умови правильних unit тестів
• Один тест одна умова
• Правильне ім'я тесту, і правильні імена змінних
• Ізольованість і незалежність від зовнішніх умов
• Коментування тестів
PhpUnit
PHPUnit — фреймворк для модульного тестування під час розробки ПЗ на PHP. PHPUnit розроблений Себастьяном Бергманом.
Переваги ...
• PHPUnit – це стандарт юніт тестування в php, більшість фреймворків використовує його: zend, YII, Symfony
• PHPUnit - інтегрований з більшістю PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm)
• PHPUnit - підтримує логування і code coverage reports
• Проста інсталяція
• Велика документація
• Інтеграція з Селеніумом
• Mockery (існують моки для бази даних, файлової системи, )
• Швидкість виконання тестів
Недоліки ...
• Щоб писати юніт тести потрібно мати навики програмування
• Вміти розбиратися в чужому коді
• Нехватає веб інтерфейсу, лише консольний запуск
Альтернатива ?
• Simple Test
Інсталяція ...
PHPUnit потрібно встановлювати з допомогою установника PEAR, (Репозиторій розширень та програм для PHP) який надає систему для поширення PHP пакетів.
pear config-set auto_discover 1 pear install pear.phpunit.de/PHPUnit
Основні командиphpunit --helpPHPUnit 3.7.0 by Sebastian Bergmann.Usage: phpunit [switches] UnitTest [UnitTest.php]phpunit [switches] <directory>--log-junit <file> Log test execution in JUnit XML format to file--log-tap <file> Log test execution in TAP format to file.--log-json <file> Log test execution in JSON format.--coverage-clover <file> Generate code coverage report in Clover XML format.--coverage-html <dir> Generate code coverage report in HTML format.--coverage-php <file> Serialize PHP_CodeCoverage object to file.--filter <pattern> Filter which tests to run.--group ... Only runs tests from the specified group
(s).--repeat <times> Runs the test(s) repeatedly.--testdox Report test execution progress in TestDox format.--stop-on-failure Stop execution upon first error or failure.--stop-on-skipped Stop execution upon first skipped test.--stop-on-incomplete Stop execution upon first incomplete test.--debug Display debbuging information during test execution.--bootstrap <file> A "bootstrap" PHP file that is run before the tests.-c|--configuration <file> Read configuration from XML file.--no-configuration Ignore default configuration file (phpunit.xml).
The XML Configuration File<phpunit backupGlobals="true" backupStaticAttributes="false" <!--bootstrap="/path/to/bootstrap.php"--> cacheTokens="true" colors="false" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" forceCoversAnnotation="false" mapTestClassNameToCoveredClassName="false"
processIsolation="false" stopOnError="false" stopOnFailure="false" stopOnIncomplete="false" stopOnSkipped="false" testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader" <!--testSuiteLoaderFile="/path/to/StandardTestSuiteLoader.php"--> strict="false" verbose="false"> <!-- ... --></phpunit>
Test Suites
<testsuites> <testsuite name="My Test Suite"> <directory>/path/to/*Test.php files</directory> <file>/path/to/MyTest.php</file> <exclude>/path/to/exclude</exclude> </testsuite></testsuites>
Including and Excluding Files for Code Coverage
<filter> <blacklist> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> <exclude> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> </exclude> </blacklist> <whitelist processUncoveredFilesFromWhitelist="true"> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> <exclude> <directory suffix=".php">/path/to/files</directory> <file>/path/to/file</file> </exclude> </whitelist></filter>
Зв'язки між тестами<?php
class StackTest extends PHPUnit_Framework_TestCase{ public function testEmpty() { $stack = array(); $this->assertEmpty($stack); return $stack; } /** * @depends testEmpty */ public function testPush(array $stack) { array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertNotEmpty($stack); return $stack; }
Провайдери даннихclass DataTest extends PHPUnit_Framework_TestCase
{ /** * @dataProvider provider */ public function testAdd($a, $b, $c) { $this->assertEquals($c, $a + $b); } public function provider() { return array( array(0, 0, 0), array(0, 1, 1), array(1, 0, 1), array(1, 1, 3) ); }}
Провайдери даннихphpunit DataTestPHPUnit 3.7.0 by Sebastian Bergmann.
...F
Time: 0 seconds, Memory: 5.75Mb
There was 1 failure:
1) DataTest::testAdd with data set #3 (1, 1, 3)Failed asserting that 2 matches expected 3.
/home/sb/DataTest.php:9
FAILURES!
Тестування Exceptionsclass ExceptionTest extends PHPUnit_Framework_TestCase{ /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Right Message */ public function testExceptionHasRightMessage() { throw new InvalidArgumentException(‘Right Message’, 10); } /** * @expectedException InvalidArgumentException * @expectedExceptionCode 20 */ public function testExceptionHasRightCode() { throw new InvalidArgumentException('Some Message', 20); }
Тестування Exceptionsclass ExceptionTest extends PHPUnit_Framework_TestCase { public function testException() {$value = false; try { // ... Код, который вызывает исключение ... } catch (InvalidArgumentException $expected) {
$value = true; } $this->assertTrue($value); }}
Asserts• assertArrayHasKey()• assertContains()• assertCount()• assertEmpty()• assertEquals()• assertFalse()• assertGreaterThan()• assertGreaterThanOrEqual()• assertInstanceOf()• assertLessThan()• assertLessThanOrEqual()• assertNull()• assertRegExp()• assertStringEndsWith()• assertStringEqualsFile()• assertStringStartsWith()• assertTrue()
Incomplete and Skipped Testsclass SampleTest extends PHPUnit_Framework_TestCase{ public function testSomething() { // Optional: Test anything here, if you want. $this->assertTrue(TRUE, 'This should already work.'); // Stop here and mark this test as incomplete. $this->markTestIncomplete( 'This test has not been implemented yet.' ); }
Incomplete and Skipped Testsclass DatabaseTest extends PHPUnit_Framework_TestCase{ protected function setUp() { if (!extension_loaded('mysqli')) { $this->markTestSkipped( 'The MySQLi extension is not available.' ); } } public function testConnection() { // ... }}
Дякую за увагу :)
Тренінг провів:Музичишин Ярослав