Repliquei o código que vi na video-aula 4 do módulo 4. Testes automatizados, mas na execução a minha variável baos
(responsável por armazer as strings) está vazia.
Meu código:
public class AbrigoServiceTest {
private ClientHttpConfiguration client = mock(ClientHttpConfiguration.class);
private HttpResponse<String> response = mock(HttpResponse.class);
private AbrigoService abrigoService = new AbrigoService(client);
private Abrigo abrigo = new Abrigo("Teste", "61981880392", "abrigo_alura@gmail.com");
@Test
public void deveVerificarSeDispararRequisicaoGetSeraChamado() throws IOException, InterruptedException {
abrigo.setId(0L);
String expectedAbrigosCadastrados = "Abrigos cadastrados:";
String expectedIdENome = "0 - Teste";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(baos);
System.out.println(printStream);
when(response.body()).thenReturn("[{" + abrigo.toString() + "}]");
when(client.dispararRequisicaoGet(anyString())).thenReturn(response);
abrigoService.listarAbrigo();
String[] lines = baos.toString(StandardCharsets.UTF_8).split(System.lineSeparator());
System.out.println(Arrays.toString(lines)); // adicionado para verificar o conteúdo de lines
String actualAbrigosCadastrados = lines[0];
String actualIdENome = lines[1];
Assertions.assertEquals(expectedAbrigosCadastrados, actualAbrigosCadastrados);
Assertions.assertEquals(expectedIdENome, actualIdENome);
}
}
Resultado da execução do teste:
Connected to the target VM, address: '127.0.0.1:51449', transport: 'socket'
WARNING: A Java agent has been loaded dynamically (C:\Users\lucas\.m2\repository\net\bytebuddy\byte-buddy-agent\1.14.12\byte-buddy-agent-1.14.12.jar)
WARNING: If a serviceability tool is in use, please run with -XX:+EnableDynamicAgentLoading to hide this warning
WARNING: If a serviceability tool is not in use, please run with -Djdk.instrument.traceUsage for more information
WARNING: Dynamic loading of agents will be disallowed by default in a future release
OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
java.io.PrintStream@4f20a5e0
Abrigos cadastrados:
0 - Teste
[]
java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at br.com.alura.service.AbrigoServiceTest.deveVerificarSeDispararRequisicaoGetSeraChamado(AbrigoServiceTest.java:44)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
Disconnected from the target VM, address: '127.0.0.1:51449', transport: 'socket'
Process finished with exit code -1
Debug da linha 41 (String[] lines = ...
):