Share
Embed
Transcript
74 slides
-
Alexey Solodkiy · 16th of March Зачем и как писать
качественные Unit-тесты -
1. Что такое качественный unit-тест? 2. Как писать такие тесты?
3. Как сделать это на практике? -
1) Тесты помогают делать продакшен стабильным • регрессионное тестирование •
фиксация контрактов -
2) Тесты повышают удобство разработки • ускорение обратной связи •
упрощение рефакторинга • тесты — это документация -
3) Тесты организуют ваш код • делают ваш код контрактным
• тесты заставляют вас думать о граничных условиях -
• стабильный • падает на багах • устойчивый к рефакторингу
• быстрый • не зависит от окружения • понятный -
• нестабильный • проходит на багах • ломкий • медленный
• работает только в определённом окружении • сложный -
Контракт модуля — то, какие ожидания у вас есть от
модуля, а у модуля — от вас -
В контракт функции может входить: • диапазон входных параметров (предусловия)
• ожидаемый результат (постусловия) • условия возникновения исключений • результат на граничных условиях -
Методы фиксации контракта: • типизация • assert • unit-тесты! •
комментарии • документация -
Какие условия контракта нужно проверять: • полезную работу • граничные
условия • исключения -
Чистой называется функция, которая: • является детерминированной • не обладает
побочными эффектами -
Функция называется детерминированной, когда для одного и того же
набора входных значений она возвращает одинаковый результат. -
Побочный эффект — любое взаимодействие с окружением (чтение и запись
файлов, глобальных переменных, любая работа с сетью) -
Чистая функция всегда однозначно преобразует входные параметры в выходные, никак
при этом не взаимодействуя с окружением Input Output [2, 4, 5] => array_sum => 11 -
Процедура Чистая функция Не детерминирована или есть побочный эффект
Примеры: rand() date() file_get_contents() PDO::query() Детерминированность Отсутствие побочных эффектов Примеры: abs() array_sum() count() -
Если ваш unit-тест будет чистой функцией, то он будет: •
быстрым • стабильным • не зависимым от окружения -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Контракт usersManager::userRegister: 1) При успешной регистрации пользователь будет добавлен в
таблицу, и ему на почту будет отправлен сгенерированный пароль 2) Метод возвращает id пользователя в базе 3) Страна пользователя определяется по доменной зоне email 4) Если такой пользователь уже есть а базе — кидаем DuplicateUserException -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций Входы -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций Выходы -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
Function testAbs($number, $expected_result) { $actual_result = abs($number) $this->assertEquals($expected_result, $actual_result); }
Function absProvider() { return [ [1, 1], [-5, 5], [5, 5] ]; } Тестирование чистых функций -
• плохие тесты хуже, чем их отсутствие • unit-тесты —
это инструмент проверки контрактов • код должен быть контрактным, если вы хотите тестировать его unit-тестами • тестируйте контракт, а не реализацию • unit-тесты подходят только для чистых функций -
Alexey Solodkiy email: [email protected] tg: @solodkiy CHEERS! [work@MacBook-Pro-Alexey ~/examples]# ./vendor/bin/phpunit
tests/UsersManagerTest.php PHPUnit 7.5.6 by Sebastian Bergmann and contributors. ..... 5 / 5 (100%) Time: 88 ms, Memory: 4.00 MB OK (5 tests, 5 assertions)