Digamos que precisamos verificar o seguinte método.
/**
* Prints {@code hello, world}, to the {@link System#out}, followed by a system dependent line separator.
*
* @param args command line arguments.
*/
public static void main(String... args) {
System.out.printf("hello, world%n"); // %n !!!!!!
}
Agora podemos verificar se o método imprime o hello, world
.
/**
* Verifies that the {@link HelloWorld#main(String...)} method prints {@code hello, world}, to the
* {@link System#out}, followed by a system-dependent line separator.
*
* @author Jin Kwon <onacit_at_gmail.com>
* @see System#lineSeparator()
*/
@DisplayName("main(args) prints 'hello, world' followed by a system-dependent line separator")
@Test
public void main_PrintHelloWorld_() {
final var out = System.out;
try {
// --------------------------------------------------------------------------------------------------- given
final var buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));
// ---------------------------------------------------------------------------------------------------- when
HelloWorld.main();
// ---------------------------------------------------------------------------------------------------- then
final var actual = buffer.toByteArray();
final var expected = ("hello, world" + System.lineSeparator()).getBytes(StandardCharsets.US_ASCII);
Assertions.assertArrayEquals(actual, expected);
} finally {
System.setOut(out);
}
}
A parte questionável é o .getBytes(StandardCharsets.US_ASCII)
.
Não acho errado presumir que o separador de linha dependente do sistema codifica com US_ASCII
.
O Charset#defaultCharset() é adequado para o %n
?
Você deve usar a mesma codificação que codificou a matriz de bytes retornada por
buffer.toByteArray()
.É o
PrintStream
trabalho do 's transformar strings em bytes, então qual codificação vocêPrintStream
usa? Você criou oPrintStream
chamando este construtor . A documentação diz:Então você deve usar
Charset.defaultCharset()
para codificar a string esperada em uma matriz de bytes.Considere também passar o seu próprio
Charset
para o construtorPrintStream
using this e use o mesmo charset para codificar a string esperada. Dessa forma, você deixa bem claro que está usando o charset correto.