furniture
Inflatable Water Slide

Un solo valor de retorno

January 27th, 2012

Hay un mal que se esta extendiendo por la aplicación en las últimas semanas. Es el ResponseDTO. Es un objeto plano, tiene un campo "success" de tipo boolean y un campo "message" de tipo string. Debía llamarse Response pero colisionaba, así que se quedó con un mal nombre. Si le hubiesemos llamado ControllerResponse seguramente no se hubiese usado en las otras capas de la aplicación porque hubiese dado más pistas a quienes lo fuesen usar, de que su lugar es la capa controller. Sin embargo se ha colado en muchas capas de backend y no es una buena práctica:

Los metodos y funciones deben devolver un solo resultado y en ocasiones, ninguno (void). ResponseDTO se puede considerar "un solo resultado" cuando los campos "success" y "message" se necesitan el uno al otro, tal que no tiene sentido el objeto sin los dos campos. Es decir cuando el objeto es lo más atómico que la operación puede devolver. ResponseDTO se ideo para enviar a cliente (js) respuesta a determinados comandos que solicita al servidor pero no debería usarse en las otras capas de la aplicacion.

¿Dónde lo usamos mal? Tenemos métodos con un nombre interrogativo que denotan retorno boolean y sin embargo devuelven uno de estos ResponseDTO:

  • IsExistingUser
  • DoesPolicyExists
  • IsValidInput

Para cualquiera que lea la API, no es intuitivo. ¿Para qué sirve el "message" del objeto cuando el método "IsExistingUser" retorna? Para nada.

En la validación, puede tener sentido este objeto response dependiendo del contexto: Si el error de validación puede considerarse una circunstancia excepcional, entonces lo mejor es lanzar una excepción que alguien de nivel superior recogerá. Por tanto, sobra el objeto response ya que la excepción llevará el mensaje de validación particular. Si un problema de validación no se considera una circunstancia excepcional, entonces puede estar bien devolver el response con su success puesto  a false y su mensaje concreto.

Más sitios donde lo usamos mal: Métodos que disparan acciones hacia fuera de nuestro sistema

  •  SendEmail
  •  SaveUser

Los métodos que provocan acciones que salen de los límites de nuestro código (acceso a BD, a un servidor de correo, etc) no pueden garantizar la correcta consumación de la acción. Por tanto, jugar a devolver boolean para exito o fracaso es engañarnos.
Es preferible un método void que funciona sin hacer ruido cuando todo va bien y que lanza excepciones cuando se encuentra con una situación inesperada. Por ejemplo, el método que solicita el envio de un email, puede defenderse de excepciones que provoque la libreria de SMTP y traducirlas en excepciones de nuestro dominio, tales como EmailSendFailure (una excepción nuestra que hereda de ApplicationException).

¿Y es tan grave que usemos el ResponseDTO? Sí que lo es porque el código que consume esos métodos se convierte en spaguetti:

var isNotValidData = !InputValidator.ValidateUserData(
                          policyHolder.Person).success;
if (isNotValidData)
{
	response.message = Strings.T("Los datos son incorrectos.");
	return response;
}

Del método "ValidateUserData" sólo nos interesa el campo "success", el mensaje lo está generando el llamador. No sólo es raro de leer sino que es un coñazo a la hora de escribir tests de interacción. Cuando queremos que en un test de colaboración, este método devuelva falso, tenemos que especificar que devuelva un objeto con un campo a falso. Si fuera boolean, no tendriamos que especificar nada porque el valor por defecto sería false. Esto va al hilo del posts de los tests de interacción limpios.

En el caso de métodos de acción como el envio de email, es incluso peor porque quien consume el método pensará que con un resultado verdadero el email ha llegado a su destino, como si eso lo pudiesemos asegurar de alguna manera.

Para saber qué debe devolver un método, este debe tener una única responsabilidad y debemos saber cual es. Y la mejor manera de saberlo, para mi siempre es escribir el test antes que el código.

 

Cleaner interaction tests

January 26th, 2012

Note: this post will probably evolve, the text will be updated as I need it.

In order to write cleaner interaction tests (those which use test doubles; mocks, spies, stubs) you should understand how your test doubles framework works. Interaction tests can be extremely difficult to read and maintain and very fragile if you don't pay enough attention. We will review Mockito, Moq, Jasmine and pyDoubles.

Mockito and Moq create a double object by inheriting the original and overriding its methods. pyDoubles uses interception rather than inheritance. Jasmine is different because it does not double the whole object, but just the method you spy on. So there is a big difference: Mockito, Moq and pyDoubles replace the whole object while Jasmine replaces just one method.

So Jasmine leaves space for a bad testing practice: Spy on one method of the object while testing other method of the same object. Interaction tests are intentded for object collaboration. Testing that one method calls another method within the same object is not recommended. It means that the object has more than one responsibility or that you want to know more about the object's inner behavior than you should, so you are breaking encapsulation. This is not a Jasmine problem, the problem is yours if you don't use the tool properly.

There are three primary reasons to replace method calls on collaborators:

  1. You want to avoid a database call just to keep the test unit fast and repeatable (stub the method - use a stub object)
  2. You want the method to return some value to simulate the response (stub the method - use a stub object)
  3. You want to make sure that a call is made (spy or expect the call - use a spy or a mock object)

For case numer 1, you don't have to specify the returned value. Just use the stub object and let the framework return whatever it wants. Mockito and Moq, return the default value for the method, when no other behavior is specified:

  • If the method returns an integer, a call to that method in the stub object, will return cero (default value for integers)
  • If the method returns an object (reference type), a call to the stub method will return null (default for objects)
  • False for booleans and so on...

However, be careful with Moq because in C#, if the original method is not virtual (contains the virtual keyword), Moq can't stub it out, so the original will be called. Moq fails if you specify a behavior on that method but if you don't, it calls the original instead of returning the default value.

pyDoubles always returns None no matter the method signature.

For case numer 2, you define what the returned value should be. Using "when" in Mockito and "Setup" in Moq.

For case numer 3, you verify that a call was made:

  • Mockito: verify(double).method();
  • Moq: double.Verify(x=>x.method());
  • pyDoubles: assert_that_method(double.method).was_called()
  • Jasmine: expect(double.method).toHaveBeenCalled()

You might want to know what parameters were passed in too. In this case you can use Matchers in Mockito, Moq and pyDoubles.

Moq sample:

userRepository.Verify(x => x.SaveNewUser(
        It.Is<Person>(
        p => p.PersonalIdentificationCode == "TEST_CODE")));
 

pyDoubles sample:

assert_that_method(double.method
         ).was_called().with_args(obj_with_fields({
                            'id': 20,
                            'test_field': 'OK'}))

For Mockito samples I am waiting for my friend @regiluze to write a post on it :-) I will link it here when written.

Jasmine sample:

spyOn(double, "method").andCallFake(function(){
      expect(arguments[0].name).toEqual("Carlos");
});

Test collaborations one to one:

If the object under test has more than one collaborator, tests can be really hard to understand. I recommend expressing every collaboration in a single test:

  • A talks to B (test 1)
  • A talks to C (test 2)
  • For test1, B will be a spy o mock (you use Verify at the end). Also for test1, you don't care about C, C is just a dummy. Calls to C don't need to be configured in the double, let the framework return the default value.
  • For test2, C is the spy or the mock, you verify interaction between A and C, and do't care about B. Calls to B don't need to be configured, let the framework return whatever.
  • For test1, if the value returned by C, is necessary for the collaboration between A and B, then Ok, specify the stub result for that call to C, and verify on B.

Group the tests by setup:

Should I have a test class for every class in the production code? NO.  Tests must be grouped by their setup. This is, put those which have the same arrangement in the same test case (test class). If there are two or more interaction tests in a class, the creation of the SUT and the doubles, should not be in every test. It must be in the setup, along with the injection (doubles, are injected to the SUT as collaborator). So, if you find yourself injecting the test double to the SUT in more than one test, watch them again carefully.

 

 

Mockito Vs Moq

January 16th, 2012

Don't be confused, the title is just to get your attention. This is not a benchmark between Mockito and Moq. I need to  explain some differences to my teammates so that the transition between Mockito and Moq is softer for them.

Typical way to stub out a method call with mockito:

when(colaborator.method(argument1)).thenReturn(whateverIwant);

Same with Moq:

colaborator.Setup(x => x.method(argument1)).Returns(whateverIwant);

Obviously, the mockito way is nicer. I believe this is because of Java capabilities but I am not sure. I would like to dig into mockito's source code to see how is this possible. I will do it and blog about it soon. I used to think that it was because of the kind ot late binding supported by Java, but I am not sure.

Moq uses a lambda expression (anonymous method inlined) to tell the framework which method and how is expected to be called). The reason I use "x" for the object in the anonymous method is because it refers to "colaborator" itself so there is no point in adding more names.

The other important difference relates to the "virtual" keyword in C#. Methods in C# are final by default. You can't override them unless they contain the keyword "virtual" on its signature. Both, Mockito and Moq create test doubles by subclassing on runtime, overriding methods and implementing the fake behavior on them (as far as I know). So, if the method you want to stub is not virtual, Moq will throw a runtime exception. If it is not virtual but you don't specify any fake behavior on it, it will not throw exceptions, but worse, it will call the actual implementation. So you might be hiting the database in your unit tests inadvertedly. What I do, is that all my methods are virtual by default (I write "virtual" on their signature).

There will be more posts on this topic :-)

-->