quarta-feira, 21 de março de 2018

Are your test cases polluted with object instantiations?

You should consider using the builder pattern with the fluent syntax. A good example from the good google testing blog.

Company small = newCompany().setEmployees(2).setBoardMembers(2).build();

I have used it myself in a C# project and it is really useful as you ensure you build always valid objects, it has a high code reuse, and is very readable.
But of course there are some challenges, like what should be the default values of such objects? It is very difficult to achieve that your tests will not turn red when you modify one of this default values  under the hood (or like the British say, under the bonnet :) ).
Even thought the builder pattern is an alternative to the mother pattern at some point you will need some combination of both in order to create some quite different types of objects. Or... can it be that it is a code smell? That if this happens is because the production code is not respecting the single responsibility principle?
Also, in C# you achieve the builder pattern by using extension methods, that of course you will need to implement and maintain.

Nevertheless I highly recommend using this pattern in your tests. I know no better alternative.

Sem comentários:

Enviar um comentário

Seguidores

Contribuidores