Introduction to unit testing

24
Unit Testing Unit Testing

description

Presentanción con conceptos de que es el testing unitario. - Características - Ventajas - Excusas - Estructura de un test - Técnicas para hacer nuestro código mas testeable - Buenas prácticas - Mocks & test doubles - Herramientas

Transcript of Introduction to unit testing

Page 1: Introduction to unit testing

Unit Testing Unit Testing

Page 2: Introduction to unit testing

Federico Lozada Mostohttp://www.mostofreddy.com.ar

@mostofreddy

@mostofreddy

@federicolozadamosto

Page 3: Introduction to unit testing

Una prueba unitaria es una forma de probar el correcto funcionamiento de una unidad funcional de forma aislada.

Esto sirve para asegurar que cada unidad funcione correctamente.

Page 4: Introduction to unit testing

Características

Page 5: Introduction to unit testing

Automatizable Deben poder ejecutarse de forma automática sin intervención manual

Predecible Deben devolver el mismo resultado sin importar la cantidad de veces que se corran

Enfocada Cada test se debe estar enfocado a una unidad funcional

Page 6: Introduction to unit testing

Ejecución rápida Deben ejecutarse rápidamente

Aisladas/independiente No deben afectar a otro test, unidada funcional ni acceder a recursos del sistema

Desarrollo rápido Simples y fáciles de desarrollar

Profesional Debe ser código como si fuera producción

Page 7: Introduction to unit testing

Ventajas

Page 8: Introduction to unit testing

Mejora la calidad del código y su arquitectura

Facilita la refactorización

Documenta el código

Detecta bugs tempranamente

Ayuda a tener un código mas desacoplado

Simplifica la integración entre sistemas

Page 9: Introduction to unit testing

Excusas

Page 10: Introduction to unit testing

El código es fácil de testear

El test no forma parte del desarrollo

Los desarrolladores no quieren escribir los test

Cuesta mucho tiempo hacer los test

Testing es para QA

Page 11: Introduction to unit testing

Estructura de un test

Page 12: Introduction to unit testing

Arrange: Es la parte del test donde se configura e inicializa el test unitario

ActEs la parte donde se ejecuta el código de

la prueba unitaria

AssertEs la parte donde se prueba el resultado

del test unitario

Page 13: Introduction to unit testing

Técnicas para hacer nuestro código más testeable

There is no secret to writing tests…… there are only secrets to writing testable code!

by Misko Hevery

Page 14: Introduction to unit testing

Programar orientado a interfaces

Usar la ley de Demeter y los principios SOLID

Definir la correcta responsabilidad en cada clase y método

Evitar métodos largos

Aislar dependencias y utilizar Inversión de Control

No realizar tareas en el método constructor

Preferir la dependencia ante la herencia

Evitar el patrón Singleton

Page 15: Introduction to unit testing

Buenas prácticas

Page 16: Introduction to unit testing

Cada test debe ser independiente al resto

Un test debe probar solo una unidad lógica

Debe haber un solo assert por test

Nombre descriptivo

Implementar test dobles para las dependencias

Page 17: Introduction to unit testing

Mocks & test doubles

Page 18: Introduction to unit testing

Sometimes it is just plain hard to test the system under test (SUT) because it depends on other components that

cannot be used in the test environment. This could be because they aren't available,

they will not return the results needed for the test or because executing them would have

undesirable side effects. In other cases, our test strategy requires us to have more control

or visibility of the internal behavior of the SUT.

When we are writing a test in which we cannot (or chose not to) use a real depended-on component (DOC),

we can replace it with a Test Double. The Test Double doesn't have to behave exactly like the real DOC;

it merely has to provide the same API as the real one so that the SUT thinks it is the real one!

– Gerard Meszaros

Page 19: Introduction to unit testing

Mock: Un mock de una interfaz nos sirve para confirmar que los métodos de la interfaz se han llamado correctamente durante la ejecución del test.

StubReemplaza/simula una dependencia a una clase/módulo. El test tiene

el control sobre el Stub y puede predefinir valores de respuesta.

FakeClase programada para generar objetos que aparentan

un funcionamiento correcto.

Page 20: Introduction to unit testing

Dummy: Objetos usados para rellenar o ser pasados por parámetro. De implementación pueden estar vacíos, ya que no van a ser usados directamente.

SpyStub pero además de cumplir su función, almacena información

como los métodos llamados.

Page 21: Introduction to unit testing

Herramientas

Page 22: Introduction to unit testing

PHP ............................. phpunit

Java ............................... JUnit

Net ................................ NUnit

Smalltalk ................. Sunit

Python ..................... PyUnit

Ruby ....................... Test::Unit

Page 23: Introduction to unit testing

¿Preguntas?

Page 24: Introduction to unit testing

@mostofreddy

@mostofreddy

@federicolozadamosto

Federico Lozada Mostohttp://www.mostofreddy.com.ar