php unit. y. muzychushun

21
Модульне тестування і PhpUnit

Upload: hrdepartment

Post on 17-May-2015

92 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Php unit. Y. Muzychushun

Модульне тестування і

PhpUnit

Page 2: Php unit. Y. Muzychushun

Модульне тестування ...?

Модульне тестування, або юніт-тестування (англ. unit testing) - процес у програмуванні, що дозволяє перевірити на коректність окремі модулі вихідного коду програми.

Ідея полягає в тому, щоб писати тести для кожної функції або методу. Це дозволяє досить швидко перевірити, чи не призвела чергове зміна коду до до появи помилок у вже відтестованих місцях програми, а також полегшує виявлення та усунення таких помилок.

Page 3: Php unit. Y. Muzychushun

Умови правильних unit тестів

• Один тест одна умова

• Правильне ім'я тесту, і правильні імена змінних

• Ізольованість і незалежність від зовнішніх умов

• Коментування тестів

Page 4: Php unit. Y. Muzychushun

PhpUnit

PHPUnit — фреймворк для модульного тестування під час розробки ПЗ на PHP. PHPUnit розроблений Себастьяном Бергманом.

Page 5: Php unit. Y. Muzychushun

Переваги ...

• PHPUnit – це стандарт юніт тестування в php, більшість фреймворків використовує його: zend, YII, Symfony

• PHPUnit - інтегрований з більшістю PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm)

• PHPUnit - підтримує логування і code coverage reports

• Проста інсталяція

• Велика документація

• Інтеграція з Селеніумом

• Mockery (існують моки для бази даних, файлової системи, )

• Швидкість виконання тестів

Page 6: Php unit. Y. Muzychushun

Недоліки ...

• Щоб писати юніт тести потрібно мати навики програмування

• Вміти розбиратися в чужому коді

• Нехватає веб інтерфейсу, лише консольний запуск

Page 7: Php unit. Y. Muzychushun

Альтернатива ?

• Simple Test

Page 8: Php unit. Y. Muzychushun

Інсталяція ...

PHPUnit потрібно встановлювати з допомогою установника PEAR, (Репозиторій розширень та програм для PHP) який надає систему для поширення PHP пакетів.

pear config-set auto_discover 1 pear install pear.phpunit.de/PHPUnit

Page 9: Php unit. Y. Muzychushun

Основні команди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).

Page 10: Php unit. Y. Muzychushun

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>

Page 11: Php unit. Y. Muzychushun

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>

Page 12: Php unit. Y. Muzychushun

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>

Page 13: Php unit. Y. Muzychushun

Зв'язки між тестами<?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; }

Page 14: Php unit. Y. Muzychushun

Провайдери данних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) ); }}

Page 15: Php unit. Y. Muzychushun

Провайдери данних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!

Page 16: Php unit. Y. Muzychushun

Тестування 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); }

Page 17: Php unit. Y. Muzychushun

Тестування Exceptionsclass ExceptionTest extends PHPUnit_Framework_TestCase { public function testException() {$value = false; try { // ... Код, который вызывает исключение ... } catch (InvalidArgumentException $expected) {

$value = true; } $this->assertTrue($value); }}

Page 18: Php unit. Y. Muzychushun

Asserts• assertArrayHasKey()• assertContains()• assertCount()• assertEmpty()• assertEquals()• assertFalse()• assertGreaterThan()• assertGreaterThanOrEqual()• assertInstanceOf()• assertLessThan()• assertLessThanOrEqual()• assertNull()• assertRegExp()• assertStringEndsWith()• assertStringEqualsFile()• assertStringStartsWith()• assertTrue()

Page 19: Php unit. Y. Muzychushun

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.' ); }

Page 20: Php unit. Y. Muzychushun

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() { // ... }}

Page 21: Php unit. Y. Muzychushun

Дякую за увагу :)

Тренінг провів:Музичишин Ярослав