Micro-posts sobre #testing

The class is not the unit in the London school style of TDD

Artículo muy interesante de Manuel Rivero en el blog de Codesai sobre el concepto de Unidad en testing y TDD, particularmente en la escuela outside-in mockista. Por cierto, no os perdáis sus muy intersantes y recomendables cursos.

Considering that the class is the unit in unit testing has terrible effects. If we follow this idea, we’ll use test doubles to isolate the class under test from any class that collaborates with it (its collaborators). This will produce tests that are highly coupled with implementation details, and therefore very brittle (high structure-sensitiveness)

The class is not the unit in the London school style of TDD

Snapshot Testing in the Backend

Hace un tiempo me contactaron desde The Test Tribe, una comunidad de testers en India, para invitarme a colaborar en su blog. Toda una sorpresa que hubiesen encontrado un artículo mío en inglés. Aprovechando que estaba en pleno desarrollo de Golden, escribí un artículo sobre snapshot testing en el backend. Gracias a Shrutika Ranjan, por la invitación.

Este es el resultado:

Snapshot testing is a methodology in which we collect the subject-under-test’s output and use it as the criterion for the subsequent test runs. We call this collected output snapshot because it captures the behavior of the subject-under-test (SUT) at a given moment in time. This defines a regression test as our goal is to be sure that future changes in the subject-under-test don’t affect its behavior. Of course, we should check that the snapshot is correct.

Snapshot Testing in the Backend

Golden, librería de snapshot testing en Go

Golden es una librería de snapshot testing que he creado para Go. Después de unas semanas de trabajo, ya está declarada estable y he publicado la versión v1.0.0.

En parte, como ejercicio de aprendizaje. En parte, porque no me acaban de encajar otras librerías disponibles.

Snapshot testing es una técnica bastante usada en desarrollo frontend que consiste en guardar el output de nuestro código y usarlo como criterio para ejecutar futuros tests. De este modo, creamos un test de regresión que nos asegure que mantenemos el comportamiento actual de una unidad de software.

En backend, el snapshot testing no es tan usado, pero hay muchos casos de uso para esta técnica: objetos complejos, generación de archivos de todo tipo (JSON, CSV, XML, etc.) para los que es costoso desarrollar un test basado en aserciones.

Además, esta técnica es muy potente usada con código legacy o, en general, con código que no tiene tests. Nos permite obtener una buena cobertura rápidamente, antes de intervenir en un código.

Golden, además de snapshot testing, nos permite trabajar con approval testing. En esta modalidad, lo que hacemos es mantener el test fallando a propósito hasta que el snapshot que se ha generado sea revisado por nosotras o por una experta del dominio que nos pueda decir si el output es correcto o no. Cuando nos satisface, “aprobamos” el snapshot y lo usamos como criterio en los tests futuros.

Approval testing es una técnica adecuada cuando estamos escribiendo código nuevo que genera objetos complejos o documentos.

Finalmente, Golden ofrece la posibilidad de realizar los tests combinatorios de la técnica Golden Master. Esta técnica consiste en bombardear el código a base de llamadas con distintas combinaciones de sus parámetros, de tal modo que lo forcemos a recorrer todos sus posibles flujos de ejecución.

Para ello, no tenemos más que indicarle a Golden listas de valores para cada parámetro de entrada de la unidad bajo test y generará todas las combinaciones posibles. Esta técnica puede ayudarnos a obtener una cobertura completa de un código existente sin tener que preocuparnos de entenderlo en profundidad. Una vez que hemos generado el “golden master” y estamos protegidas por el test, podemos empezar a aplicar técnicas de refactor para mejorar su diseño.

Golden: librería de snapshot testing en Go

Fifty Quick Ideas to Improve Your Tests

Este librito de Gojko Adzic, David Evans y Tom Roden ($10 en Leanpub propone exactamente 50 ideas a considerar para diseñar nuestra estrategia de testing. Me encanta particularmente esta serie de heurísticas emocionales para decidir qué tests hacer. Sencillamente genial:

Here is our set of emotional heuristics to stimulate test design, taking an emotional roller coaster of a ride along the way:

The scary path – if this path was followed it would really tear the house down, and everything else with it. Flush out those areas of the highest risk to the stakeholders. Think what would scare each stakeholder the most about this piece of functionality or change.

The happy path – the key example, positive test, that describes the straightforward case. This is the simplest path through the particular area of behaviour and functionality that we can think of, it is the simplest user interaction and we expect it to pass every time (other than its first ever run maybe).

The angry path – with the angry path we are looking for tests which we think will make the application react badly, throw errors and get cross with us for not playing nicely. These might be validation errors, bad inputs, logic errors.

The delinquent path – consider the security risks that need testing, like authentication, authorisation, permissions, data confidentiality and so on.

The embarrassing path – think of the things that, should they break, would cause huge embarrassment all round. Even if they wouldn’t be an immediate catastrophe in loss of business they might have a significant impact on credibility, internally or externally. This could be as simple as something like spelling quality as ‘Qality’, as we once saw on a testing journal (just think of the glee on all those testers’ faces).

The desolate path – provide the application or component with bleakness. Try zeros, nulls, blanks or missing data, truncated data and any other kind of incomplete input, file or event that might cause some sort of equally desolate reaction.

The forgetful path – fill up all the memory and CPU capacity so that the application has nowhere left to store anything. See how forgetful it becomes and whether it starts losing data, either something that had just been stored, or something it was already holding.

The indecisive path – simulate being an indecisive user, unable to quite settle on one course of action. Turn things on and off, clicking back buttons on the browser, move between breadcrumb trails with half-entered data. These kinds of actions can cause errors in what the system remembers as the last known state.

The greedy path – select everything, tick every box, opt into every option, order lots of everything, just generally load up the functionality with as much of everything as it allows to see how it behaves.

The stressful path – find the breaking point of the functions and components so you can see what scale of solution you currently have and give you projections for future changes in business volumes.

Fifty Quick Ideas to Improve Your Tests

Understanding Legacy Code with TCR

Una sesión de live coding con Kent Beck y Kelly Sutton explicando cómo puedes usar el workflow Test Commit Or Revert para probar hipótesis sobre un código que no conoces.

Consiste en ir escribiendo pequeños tests con el comportamiento que supones o esperas. Si aciertas, el test se queda. Y, si no, el test desaparece.

Oh… we lost it. We are so sad.

Understanding Legacy Code with TCR