Skip to content

Instantly share code, notes, and snippets.

Created July 29, 2013 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/6105990 to your computer and use it in GitHub Desktop.
Save anonymous/6105990 to your computer and use it in GitHub Desktop.
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
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