Home > database >  Assert OutputStreamWriter contains correct instance of OutputStream
Assert OutputStreamWriter contains correct instance of OutputStream

Time:11-16

I'm writing a test for a method that returns Writer for different extension files.

For .gz returns new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)), StandardCharsets.UTF_8)

For non compressed files returns new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);

How to assert that OutputStreamWriter contains GZIPOutputStream or FileOutputStream?

CodePudding user response:

OutputStreamWriter extends Writer. Your FileOutputStream or GZIPOutputStream is set as: protected Object lock inside Writer class.

 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File("file_patch")), StandardCharsets.UTF_8);
    Field lock = outputStreamWriter.getClass().getSuperclass().getDeclaredField("lock");
    lock.setAccessible(true);
    Object o = lock.get(outputStreamWriter);
    Class<?> theClassYouNeed = o.getClass();

Now you just need to check if theClassYouNeed is the expected class.

CodePudding user response:

Consider splitting your code two testable methods, one for underlying OutputStream which you could test with instanceof GZIPOutputStream (or not true depending on the file), and the other method with Writer tests - which verify the UTF-8 output file is as expected (with or without GZIP).

You can easily adapt this example if you use File not Path:

public static OutputStream newOutputStream(final Path file) throws IOException {
    // identify gzipped data files
    boolean isGZ = file.getFileName().toString().toLowerCase().endsWith(".gz");
    OutputStream out = Files.newOutputStream(file);
    return isGZ ? new GZIPOutputStream(out, 8192) : out;
}
public static OutputStreamWriter newWriter(final Path file) throws IOException {
    return new OutputStreamWriter(newOutputStream(file), StandardCharsets.UTF_8);
}
  • Related