2. Модульне тестування ...?
Модульне тестування, або юніт-тестування (англ. unit
testing) - процес у програмуванні, що дозволяє перевірити на
коректність окремі модулі вихідного коду програми.
Ідея полягає в тому, щоб писати тести для кожної функції або
методу. Це дозволяє досить швидко перевірити, чи не призвела
чергове зміна коду до до появи помилок у вже відтестованих
місцях програми, а також полегшує виявлення та усунення таких
помилок.
3. Умови правильних unit тестів
•
Один тест одна умова
•
Правильне ім'я тесту, і правильні імена змінних
•
Ізольованість і незалежність від зовнішніх умов
•
Коментування тестів
4. PhpUnit
PHPUnit — фреймворк для модульного тестування під час
розробки ПЗ на PHP. PHPUnit розроблений Себастьяном
Бергманом.
5. Переваги ...
•
PHPUnit – це стандарт юніт тестування в php, більшість фреймворків
використовує його: zend, YII, Symfony
•
PHPUnit - інтегрований з більшістю PHP IDE (Eclipse, Netbeans, Zend
Stuide, PHPStorm)
•
PHPUnit - підтримує логування і code coverage reports
•
Проста інсталяція
•
Велика документація
•
Інтеграція з Селеніумом
6. Недоліки ...
•
Щоб писати юніт тести потрібно мати навики програмування
•
Вміти розбиратися в чужому коді
•
Нехватає веб інтерфейсу, лише консольний запуск
8. Інсталяція ...
PHPUnit потрібно встановлювати з допомогою
установника PEAR, (Репозиторій розширень та програм
для PHP) який надає систему для поширення PHP
пакетів.
pear config-set auto_discover 1
pear install pear.phpunit.de/PHPUnit
9. Основні команди
phpunit --help
PHPUnit 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.
11. 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>
12. 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>
13. Зв'язки між тестами
<?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]);
14. Провайдери данних
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)
);
15. Провайдери данних
phpunit DataTest
PHPUnit 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
16. Тестування Exceptions
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException
InvalidArgumentException
* @expectedExceptionMessage Right Message
*/
public function testExceptionHasRightMessage()
{
throw new InvalidArgumentException(‘Right Message’, 10);
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionCode 20
17. Тестування Exceptions
class ExceptionTest extends PHPUnit_Framework_TestCase {
public function testException() {
$value = false;
try {
// ... Код, который вызывает исключение ...
}
catch (InvalidArgumentException $expected) {
$value = true;
}
$this->assertTrue($value);
19. Incomplete and Skipped Tests
class 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.'
);
}
20. Incomplete and Skipped Tests
class DatabaseTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!extension_loaded('mysqli')) {
$this->markTestSkipped(
'The MySQLi extension is not available.'
);
}
}
public function testConnection()
{