to mock or not to mock

Download To mock or not to mock

If you can't read please download the document

Upload: eloi-poch

Post on 29-Jan-2018

277 views

Category:

Software


0 download

TRANSCRIPT

  1. 1. Quines somos? Eloi Poch Jordi Llonch
  2. 2. Agenda Qu hacemos en Akamon? To test or not to test? Cmo hacemos test? Libreras de mock. Conclusiones y consejos.
  3. 3. Osiris: Nueva plataforma de servicios de Akamon. Principios: Simplicidad sobre facilidad. Qu hacemos? Calidad Funcionalidad Velocidad
  4. 4. Domain Contract Infrastructure Domain (Business Logic) Contract Infrastructure Domain (Business Logic) Applications Background Website APIsAPIsAPIs Arquitectura by Akamon APIs DBs Contract External Services Infrastructure Domain (Business Logic)
  5. 5. Calidad Pull Request Test Pair Programming by Akamon
  6. 6. To test or not to test? Todo el m undo hace tests
  7. 7. To test or not to test Los buenos test ahorran DINERO en cualquier aplicacin
  8. 8. To test or not to test
  9. 9. Testear es controvertido David Heinemeier (creador de Ruby on Rails y Fundador y CTO de Basecamp) TDD is dead. Long live testing & RailsConf 2014 Keynote - Writing Software by DHH Hangouts entre Kent Beck, DHH y M. Fowler El caso DHH
  10. 10. Cmo hacemos test? Akamon Way
  11. 11. Un feedback rpido para el cdigo que estamos escribiendo de una funcionalidad. Qu queremos de los tests?
  12. 12. Testean de manera rpida una funcionalidad. Qu hacen nuestros tests?
  13. 13. Infrastructure External Services Test Double Test Double APIs DBs Contract Domain (Business Logic)
  14. 14. Test doubles Implementacin alternativa de un colaborador (clase o servicio) Objetivo: Hacer nuestros tests rpidos. Aislar sistemas externos. Testear casos extremos.
  15. 15. Test doubles Tipos: Dummy: Implementacin no funcional. Fake: Implementacin completamente funcional pero no usable en un entorno real. Stub: Implementacin parcialmente funcional preparada nicamente para poder ser usada en el test. Spy: Stub con memoria. Mock: Spy con expectaciones sobre las llamadas a recibir que las auto-comprueba l mismo.
  16. 16. Tests Unitarios Pros Contras Rpidos No pueden probar la ausencia de errores Permiten testear todos los casos Los doubles no son conables Ayudan a encontrar problemas pronto Los doubles estn acoplados a sus implementaciones Facilitan el cambio Buena documentacin
  17. 17. Escuelas de Tests Unitarios Chicago / Classical London / Mockist nfasis Algoritmo Envo de mensajes Enfoque Resultado, estado y efectos colaterales Roles, responsabilidades e interacciones Libro Test-Driven Development by Example Growing Object Oriented Software Guided by Tests
  18. 18. Unit Testing :: Chicago School Pros: Menor riesgo de expectaciones incorrectas. Tests estables. Menos mantenimiento. Contras: Ciclo largo de Red-Green-Refactor. Explosin combinatoria de los casos a testear. Un simple bug rompe muchos tests. Ms debugging para encontrar la raz del error.
  19. 19. Unit Testing :: London School Pros: Facilita el enfoque. Baby steps. Contras: Alto riesgo de expectaciones incorrectas (el refactoring no detecta cambios en los colaboradores) Acople del test a la implementacin. Test frgiles.
  20. 20. Glosario Test Unitarios: Test del cdigo y la lgica de negocio de una funcionalidad (operaciones con el contrato del mdulo). Test double: La infraestructura y los servicios externos. Riesgo: Test demasiado profundo que no permita testear de manera simple todas las casusticas by Akamon
  21. 21. pero los test unitarios no son sucientes
  22. 22. Queremos saber si las integraciones con los sistemas externos funcionan correctamente.
  23. 23. Infrastructure External Services APIs DBs Contract Domain (Business Logic)
  24. 24. Tests de Integracin Pros Contras Conables Lentos Encontrar problemas/cambios con servicios de terceros Imposible de testear algunos casos extremos Buena documentacin
  25. 25. Test de integracin: Test de las implementaciones de los contratos/ interfaces de la infraestructura y los servicios externos. Test double: Nada. by Akamon Glosario
  26. 26. pero con test unitario e integracin todava no es suciente
  27. 27. Applications APIs Background Website APIsAPIs ? Domain Module User Module Analytics Module Marketing Module Device Module Economy Module Game Module Game Event
  28. 28. Tests de Aceptacin Pros Contras Amigables y entendibles para usuarios no tcnicos Lentos Gran conanza Complicado de testear algunos casos Buena documentacin Imposible testear algunos casos extremos Complicado localizar errores Complicados de escribir (estado inicial)
  29. 29. Glosario Test de aceptacin: Test de una funcionalidad (end-to-end black-box mode). Test double: Nada. by Akamon
  30. 30. Nuestra pirmide de tests Acceptance Integration Unit
  31. 31. Libreras mock https://github.com/Akamon/to-mock-or-not-to-mock
  32. 32. Comparativa PHPUnit 4.1 Mockery 0.9 Phake 1.1 Prophecy 1.0 Notas Invocation Count Constraint Ok Muy bueno Muy bueno Ok Mockery/Phake son mejores. Mtodos atMost() y atLeast() disponibles. Ordered Expectations Ok Bueno Ok No Mockery es mejor. Simplemente usando ordered([group]). Argument Matchers Bueno Ok Ok Ok PHPUnit es mejor. Sobre todo con la funcionalidad delta Partial Mocking Ok Muy bueno Ok No La construccin es mucho ms simple con Mockery. Mocking Demeter Chains And Fluent Interfaces Ok Muy bueno Ok Ok Muy sencillo con Mockery y un poco rebuscado con los otros. Test Doubles Ok Bueno Ok Bueno Prophecy es el nico con spies y Mockery el nico que gestiona static, nal & private
  33. 33. Otro punto de vista
  34. 34. Property-Based Testing Aproximacin totalmente diferente. No se escriben los tests, se generan. QuickCheck: Canonical framework escrito en Haskell. Cmo funciona?: Describe las entradas y salidas permitidas y las transiciones de estado. Genera aleatoriamente un gran nmero de casos de test y busca fallos. Devuelve el mnimo ejemplo de fallo. Casos de uso: Comportamientos no determinsticos y sistemas concurrentes.
  35. 35. Conclusiones En el mundo del testing lo ms importante es determinar la unidad o sistema a testear. Los tipos de tests, los doubles e incluso los frameworks dependen de la unidad o sistema a testear.
  36. 36. Consejos Evita Minimiza los dobles: Estn acoplados a la implementacin Limitan la refactorizacin pura. No son conables Pueden tener un comportamiento diferente al real. by Akamon
  37. 37. Consejos Los test unitarios testean cdigo no funcionalidad: TDD por si solo no es suciente. BDD por si solo puede ser suciente (si no te importa la lentitud). TDD + BDD = WIN by Akamon
  38. 38. Consejos Separa la lgica del test de los datos del test: Usa el @dataProvider de PHPUnit (no para los doubles). Usa el Scenario Outline de Behat. by Akamon
  39. 39. La unidad a testear: Mockists are dead. Long live classicists. Unit Tests: Isolation Mock arent stubs: Dummy, Fake, Stub and Mock TTDD (Tautological TDD): An anti-pattern The depth of tests Avoid Testing Implementation Details, Test Behaviours The Failures of "Intro to TDD" The London School of Test Driven Development Referencias
  40. 40. Test doubles: Tests doubles Mocks, fakes, stubs and dummies The little mocker Referencias
  41. 41. Contract tests (a.k.a integration tests): Integrated tests are scam (Collaboration & Contract tests) Integration contract tests Referencias
  42. 42. La pirmide de los tests: Test Pyramid Testing Pyramid: A case study Inverting the testing pyramid Testing ice-crean corn anti-pattern Referencias
  43. 43. Referencias Property-Based testing: Better than unit tests Powerful testing with test.check Testing the Hard Stuff and Staying Sane
  44. 44. Entrevistas a veteranos del TDD: Ron Jeffries (One of the founders of Extreme Programming & Agile Manifesto) Steve Freeman (Co-author of Growing Object- Oriented Software Guided by Tests) James Shore (Author of The Art of Agile Development) J.B. Rainsberger (Author of JUnit Recipes : Practical Methods for Programmer Testing Referencias
  45. 45. Preguntas? Gracias!We are hiring
  46. 46. Imgenes http://transmedialshakespeare.les.wordpress.com/2011/01/3459513455_d1288a14b9_o.jpeg http://info.fonality.com/Portals/65551/images/Presentation.jpg http://www.renders-graphiques.fr/image/upload/normal/organisateur_bloc_notes_agenda-.png http://www.luxfacta.com/wp-content/uploads/2014/01/programar.jpg http://www.kinderlandshop.es/WebRoot/StoreES2/Shops/eb0950/5020/E112/E380/66B2/C9CA/AC10/1414/0340/C05_1.jpg http://www.allpurposeabrasives.com.au/uploads/images/Quality%20Assurrance.jpg http://news.liv.ac.uk/wp-content/uploads/2013/03/knowledgeHOMEb.jpg http://www.worldnpa.org/site/wp-content/uploads/2013/01/hand-writing.jpg http://ievasapple.com/photo/images/my%20point%20of%20view.JPG http://www.snegmortgageteam.ca/wp-content/uploads/2013/12/mortgage-glossary.jpg http://birddogrealestate.net/wp-content/uploads/2012/09/Home-Toolbox.jpg http://www.balticblues-events.com/sites/default/les/images/ideas/photos/32-Live-Cooking1.jpg http://www.youwall.com/papel/on_my_way_wallpaper_fa2bb.jpg http://inheritancethelm.com/wp-content/uploads/2013/06/thankyou.jpg http://www.ngn.com.au/wp-content/uploads/2013/07/Websites-on-white.png http://hn-marketing.co.uk/wp-content/uploads/2012/09/shutterstock_12553684.jpg http://picturesofmoney.org/wp-content/uploads/2013/04/Animated-American-Money-Falling-Into-a-Pile.jpg http://st.gdefon.com/wallpapers_original/wallpapers/18716_palma_more_plyazh_pesok_oblaka_tropiki_2560x1600_(www.GdeFon.ru).jpg http://i.imgur.com/DbTGPys.gif http://media.tumblr.com/e96b538708be71104f21689d3a820b9c/tumblr_inline_n54iazp56x1raprkq.gif http://i.imgur.com/8Lpsys5.gif