Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Test-Driven Development

Test-Driven Development

Test-Driven Development o TDD es una metodología de desarrollo de software que intenta de manera proactiva garantizar que nuestro código funciona como debería, además de prevenir y reducir el número de defectos y bugs de nuestro código. La idea principal de esta metodología es realizar de forma inicial las pruebas unitarias para el código que tenemos que implementar e ir creando un conjunto de pruebas que nos avisen inmediatamente si hemos introducido algún cambio que modifique su funcionamiento.

Desde que el TDD fue "redescubierto" por Kent Beck, ha sido una de las técnicas ágiles que más difusión ha alcanzado y goza de especial popularidad en estos momentos. Sin embargo, a menudo es mal aplicado y los equipos que lo implementan se ven aquejados de problemas comunes, que terminan haciendo que se abandone. Muchos desarrolladores piensan que desarrollar tests unitarios sale más caro, que es una pérdida de tiempo, pero sólo una reflexión, ¿cuánto tiempo pasáis depurando vuestro código? ¿cuántas veces habéis arreglado algún bug que se podría haber detectado con un test unitario?

En esta charla trataremos los siguientes puntos:
- Hablar sobre el origen de TDD
- Explicar brevemente cómo se realiza TDD
- Entrar en detalle de las ventajas e inconvenientes de TDD
- Justificar por qué TDD funciona de esta manera y qué conseguimos con ello
- Ver el lado oscuro de TDD trayendo opiniones relevantes que critican TDD y, a partir de ellas, ver qué cosas se podrían mejorar

4cae070608be3489262fe419c03498dc?s=128

Adrián Matellanes

April 19, 2018
Tweet

Transcript

  1. Test-Driven Development Adrián Matellanes

  2. None
  3. What is TDD?

  4. A development technique where you must first write a test

    that fails before you write new code that passes the new test
  5. Kent Beck rediscovered this technique in the 1990s

  6. What is a test?

  7. A procedure intended to establish the quality, performance, or reliability

    of something.
  8. <?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function

    testTalk() { $user = new User(); $actual = $user->talk(); $expected = "Hello world!"; $this->assertEquals($expected, $actual); unset($user); } }
  9. <?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function

    testTalk() { $user = new User(); $actual = $user->talk(); $expected = "Hello world!"; $this->assertEquals($expected, $actual); unset($user); } } Setup
  10. <?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function

    testTalk() { $user = new User(); $actual = $user->talk(); $expected = "Hello world!"; $this->assertEquals($expected, $actual); unset($user); } } Execution
  11. <?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function

    testTalk() { $user = new User(); $actual = $user->talk(); $expected = "Hello world!"; $this->assertEquals($expected, $actual); unset($user); } } Validation
  12. <?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function

    testTalk() { $user = new User(); $actual = $user->talk(); $expected = "Hello world!"; $this->assertEquals($expected, $actual); unset($user); } } Teardown
  13. Testing Methods

  14. Black box White box

  15. Categories of Tests

  16. Unit Integration Behavioral

  17. Unit Behavioral Integration

  18. Test Doubles

  19. Dummy Fake Stub Spy Mock

  20. TDD Schools

  21. London School Detroit School

  22. Why developers not writing tests?

  23. No time No budget Write once project finishes We do

    not know how to write
  24. “If it's worth building, it's worth testing. If it's not

    worth testing, why are you wasting your time working on it?” Scott Ambler
  25. What is the goal of TDD?

  26. Write clean code that works

  27. “The only way to make the deadline — the only

    way to constantly go fast — is to keep the code as clean as possible at all times.” Robert C. Martin
  28. What makes a design good?

  29. The 7 Design Smells of Bad Code

  30. Rigidity Fragility Immobility Viscosity Needless Repetition Opacity Needless Complexity

  31. How TDD works?

  32. None
  33. None
  34. Red Write a failing test

  35. Green Make the test pass

  36. Refactor Make it better

  37. Technical Debt

  38. None
  39. “Perfect is the enemy of good.” Voltaire

  40. Why do you test-drive code?

  41. Predictability

  42. Courage

  43. Documentation

  44. Cleaner Code

  45. Gamification

  46. Reduced debugging effort

  47. More productive

  48. Automated

  49. Emergent Design

  50. Coverage

  51. Code coverage refers to the amount of code covered by

    test cases
  52. The tragedy of 100% code coverage

  53. <?php use PHPUnit\Framework\TestCase; function division($a, $b) { return $a /

    $b; } class CalculatorTest extends TestCase { public function testDivision() { $result = division(10, 5); $expected = 2; $this->assertEquals($expected, $result); } }
  54. None
  55. None
  56. None
  57. None
  58. None
  59. Best Practices

  60. Keep the unit small Minimize assertions Start with the failing

    test case Fast running tests Avoid fragile tests Rerun all test cases on each failure Don’t introduce dependencies between tests Follow standard naming conventions Use mock objects
  61. The Bad Parts

  62. Hard to apply to existing legacy code Requirements misinterpretations False

    sense of security How many tests should you write? Complex scenarios Rapidly changing requirements Not having enough knowledge on unit testing and refactoring Restricted portability Writer/Reader with technical background
  63. Behavior-driven development

  64. Behavioural Test Unit Test

  65. None
  66. Scenario: Dispense $50 cash in multiple denominations Given I have

    $100 in my account And I have a card with the PIN 1234 And I push my card into the machine And I enter 1234 for my PIN And I push the button next to Withdrawal And I push the button next to Checking When I push the button next to $50 Then a $20 bill should be ejected by the cash dispenser And a $20 bill should be ejected by the cash dispenser And a $10 bill should be ejected by the cash dispenser
  67. Scenario: Dispense $50 cash in multiple denominations Given I have

    $100 in my account And I have a card with the PIN 1234 And I push my card into the machine And I enter 1234 for my PIN And I push the button next to Withdrawal And I push the button next to Checking When I push the button next to $50 Then a $20 bill should be ejected by the cash dispenser And a $20 bill should be ejected by the cash dispenser And a $10 bill should be ejected by the cash dispenser
  68. Scenario: Dispense $50 cash in multiple denominations Given I have

    $100 in my account And I have a card with the PIN 1234 And I push my card into the machine And I enter 1234 for my PIN And I push the button next to Withdrawal And I push the button next to Checking When I push the button next to $50 Then a $20 bill should be ejected by the cash dispenser And a $20 bill should be ejected by the cash dispenser And a $10 bill should be ejected by the cash dispenser
  69. Scenario: Dispense $50 cash in multiple denominations Given I have

    $100 in my account And I have a card with the PIN 1234 And I push my card into the machine And I enter 1234 for my PIN And I push the button next to Withdrawal And I push the button next to Checking When I push the button next to $50 Then a $20 bill should be ejected by the cash dispenser And a $20 bill should be ejected by the cash dispenser And a $10 bill should be ejected by the cash dispenser
  70. Scenario: Dispense $50 cash in multiple denominations Given I have

    $100 in my account And I have a card with the PIN 1234 And I push my card into the machine And I enter 1234 for my PIN And I push the button next to Withdrawal And I push the button next to Checking When I push the button next to $50 Then a $20 bill should be ejected by the cash dispenser And a $20 bill should be ejected by the cash dispenser And a $10 bill should be ejected by the cash dispenser
  71. TDD vs BDD

  72. TDD Hard to apply to existing legacy code Inside out

    Fast execution time “That is wrong” Doing the thing right Technical writer/reader Low case coverage Poor maintainability Easy to apply to existing legacy code Outside in Slow execution time “Something is wrong” Doing the right thing Business writer/reader High case coverage High maintainability BDD
  73. TDD or BDD?

  74. Final Thoughts

  75. None
  76. “It’s a skill! Learn it by using it”

  77. Do you release with failing tests? Does it depends?

  78. References Test Driven Development: By Example by Kent Beck (2002)

    Refactoring by Kent Beck and Martin Fowler (1999) Succeeding with Agile by Mike Cohn (2009) Working Effectively with Unit Tests by Jay Fields (2014) The Art of Unit Testing by Roy Osherove (2013) Software Reliability: Principles and Practices by Glenford J. Myers (1976)
  79. Thank you!