Como fazer mocking de dependências internas?
Refletindo sobre o tópico levantado aqui: http://www.polignu.org/artigo/um-padr%C3%A3o-para-mock-de-depend%C3%AAncias-internas-em-testes-de-unidade
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RotaFinderFactory { | |
private static RotaFinderFactory rotaFinderFactory = null; | |
private RotaFinderFactory() { } | |
// Singleton | |
public static RotaFinderFactory getFactory() { | |
if(rotaFinderFactory == null) { | |
rotaFinderFactory = new RotaFinderFactory(); | |
} | |
return rotaFinderFactory; | |
} | |
public RotaFinder getNewInstance() { | |
return new RotaFinder(); | |
} | |
} | |
public class Carteiro { | |
public RotaFinderFactory rotaFinderFactory; | |
public Carteiro() { | |
this.rotaFinderFactory = RotaFinderFactory.getFactory(); | |
} | |
public Carteiro(RotaFinderFactory rotaFinderFactory) { | |
this.rotaFinderFactory = rotaFinderFactory; | |
} | |
public void entrega(Carta carta) { | |
RotaFinder rotaFinder = rotaFinderFactory.getNewInstance(); | |
Endereco endereco = carta.getEnderecoDestino(); | |
Rota rota = rotaFinder(endereco); | |
// usa a rota pra entregar a carta | |
} | |
} | |
//TESTE | |
public class CarteiroTest { | |
RotaFinderFactory rotaFinderFactoryMock; | |
RotaFinder rotaFinderMock; | |
@Before | |
public void setUp() { | |
this.rotaFinderFactoryMock = … // cria mock | |
this.rotaFinderMock = … // cria mock | |
} | |
@Afer | |
public void tearDown() { | |
RotaFinderFactory.testing = false; // importante pra não afetar indevidamente outros testes | |
} | |
@Test | |
public void shouldEntregarCarta() { | |
when(rotaFinderFactoryMock.getNewInstance()).thenReturn(rotaFinderMock); | |
// testa método carteiro.entrega(carta) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment