Unit Tests

Материал из AgileWiki

Перейти к: навигация, поиск

Содержание

Определение

Обсуждения

Статьи

Unit Test-ы

Unit тесты играют ключевую роль в XP. Они позволяют быстро менять код не боясь наделать новых ошибок. Unit тест пишется для каждого класса, тест должен проверять все аспекты работы класса - тестировать все что может не работать.

Хитростью здесь является то, что тест для класса должен быть написан раньше самого класса. Это значит, что как только вы выпустите первый работающий результат, он будет поддерживаться системой тестирования. Для проведения тестов пишется специальная система тестирования со своим интерфейсом.

Unit тест для класса хранится в общем репозитории вместе с кодом класса. Никакой код не может быть выпущен без Unit теста. Перед отдачей кода разработчик должен удостовериться что все тесты проходят без ошибок. Никто не может отдать код, если все не прошли 100%. Другими словами поскольку до ваших изменений все тесты проходили, то если вы имеете ошибки, то это результат ваших изменений. Вам и исправлять. Иногда бывает неправильным или неполным код теста. В таком случае надо исправлять его.

Огромным искушением является сэкономить на Unit тестах когда мало времени. Но этим Вы только обманываете себя. Чем сложнее написать тест, тем больше времени он потом сэкономит. Это доказано практикой.

Unit тесты позволяют осуществить коллективное владение кодом. Они позволяют относительно легко пересматривать плохой код. Также Unit тесты позволяют в любой момент иметь стабильно работающую систему.

Наш опыт.

Сложно начинать писать UnitTest-ы когда уже есть система на 400000 строк. Но можно. Так что пишем. Правило такое - если меняешь код, для которого нет UnitTest-а - напиши сначала тест. Для нового кода все делается по правилам.

Как результат мы имеем заметно более качественный код. Цикл стабилизации системы перед выпуском сократился с полутора месяцев до двух-трех недель. Это при том что Unit тестами покрыто менее половины системы.

Наличие UnitTest-ов позволяет рефакторить систему. Также само написание теста обычно ведет к тому, что структура объектов становится проще. Часто сначала приходится тестировать всю подсистему, поскольку невозможно выделить один обьект из-за запутанных взаимосвязей. Потихоньку клубок распутывается и все становится ясно и красиво.

Unit Tests

Изображение:Codeownership.GIF

Unit tests are one of the corner stones of Extreme Programming (XP). But unit tests XP style is a little different. First you should create or download a Unit Test Framework to be able to create automated unit tests suites. Second you should test all classes in the system. Trivial getter and setter methods are usually omitted. And last you should try to create your Tests First, before the code.

Unit tests are released into the code repository along with the code they test. Code without tests may not be released. If a unit test is discovered to be missing it must be created at that time.

The biggest resistance to dedicating this amount of time to unit tests is a fast approaching deadline. But during the life of a project an automated test can save you a hundred times the cost to create it by finding and guarding against bugs. The harder the test is to write the more you need it because the greater your savings will be. Automated unit tests offer a pay back far greater than the cost of creation.

Another common misconception is that unit tests can be written in the last three months of the project. Unfortunately, without the unit tests development drags on and eats up those last three months and then some. Even if the time is available good unit test suites take time to evolve. Discovering all the problems that can occur takes time. In order to have a complete unit test suite when you need it you must begin creating the tests today when you don't.

Unit tests enable Collective Code Ownership. When you create unit tests you guard your functionality from being accidentally harmed. Requiring all code to pass all unit tests before it can be released ensures all functionality always works. Code ownership is not required if all classes are guarded by unit tests.

Unit tests enable Refactoring as well. After each small change the unit tests can verify that a change in structure did not introduce a change in functionality.

Building a single universal unit test suite for validation and regression testing enables frequent integration. It is possible to integrate any recent changes quickly then run your own latest version of the test suite. When a test fails your latest versions are incompatible with the team's latest versions. Fixing small problems every few hours takes less time than fixing huge problems just before the deadline. With automated unit tests it is possible to merge a set of changes with the latest released version and release in a short time.

Often adding new functionality will require changing the unit tests to reflect the functionality. While it is possible to introduce a bug in both the code and test it rarely happens in actual practice. It does occasionally happen that the test is wrong, but the code is right. This is revealed when the problem is investigated and is fixed. Creating tests independent of code, hopefully before code, sets up checks and balances and greatly improves the chances of getting it right the first time.

Unit Tests provide a safety net of regression tests and validation tests so that you can refactor and integrate effectively. As they say at the circus; never work without a net! Creating the unit test before the code helps even further by solidifying the requirements, improving developer focus, and avoid creeping elegance.

agileatlanta.org

Unit Testing is one of the most easily accepted of XP's Best Practices . Many of XP's other practices depend upon having Unit Tests. Plus, Unit Testing is gaining great acceptance in non-XP circles.

If this is a "best practice", then why don't people do it?

  • fear it will take too long
    • actually speeds us up (once it becomes 2nd nature)
  • don't know how
    • haven't been shown how
  • don't have or know about a unit testing framework
  • don't have a build process that can run them

How is it any different if done "eXtreme"?

  • more tests automated
    • even GUI testing
    • even "functional-testing"
  • Test First Programming? -- write the tests FIRST

What other practices support this practice?

What other practices are supported by this one?

How do I get started?

  • get xUnit (eg http://www.junit.org/) and study the getting started documentation
  • find or hire someone with experience with xunit and have them coach your team members 1-on-1 (pair program)
  • do william wake's test first challenge: http://xp123.com/

Next: Refactoring (path A); Simple Design (path B).

Ссылки

Личные инструменты