Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a method using a PrintWriter?

Tags:

java

csv

mockito

I have following method:

@Component
public class WriteCsvToResponse {

    private static final Logger LOGGER = LoggerFactory.getLogger(WriteCsvToResponse.class);

    public void writeStatus(PrintWriter writer, Status status) {

        try {

            ColumnPositionMappingStrategy mapStrategy
                = new ColumnPositionMappingStrategy();

            mapStrategy.setType(Status.class);

            String[] columns = new String[]{"id", "storeId", "status"};
            mapStrategy.setColumnMapping(columns);

            StatefulBeanToCsv btcsv = new StatefulBeanToCsvBuilder(writer)
                .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                .withMappingStrategy(mapStrategy)
                .withSeparator(',')
                .build();

            btcsv.write(status);

        } catch (CsvException ex) {

            LOGGER.error("Error mapping Bean to CSV", ex);
        }
    }

I have no idea how to test it properly using mockito.

Use it to wrap the object status into csv format. I used StringWriter to wrap the response in it. There are no more details left, but it seems I have to create some words to pass the validation :)

like image 889
John Avatar asked Mar 17 '26 06:03

John


2 Answers

You do not need mockito to test this method, only a java.io.StringWriter.

Here is how you can write the test for a nominal use:

@Test
void status_written_in_csv_format() {
    // Setup
    WriteCsvToResponse objectUnderTest = new WriteCsvToResponse ();
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    // Given
    Status status = ...

    // When
    objectUnderTest.writeStatus(printWriter, status);

    // Then
    String actualCsv = stringWriter.toString();
    assertThat(actualCsv.split("\n"))
       .as("Produced CSV")
       .containsExactly(
         "id,storeId,status",
         "42,142,OK");
}

This example assume some things about your Status object, but you have the general idea. For assertions, I use AssertJ, but you can do the same with JUnit5 built-in assertions.

Hope this helps !

like image 193
Loïc Le Doyen Avatar answered Mar 18 '26 19:03

Loïc Le Doyen


With a bit of a refactoring, where the Builder is a Spring Bean injected into this component.

You can then mock that builder to return a mocked StatefulBeanToCsv, specifically the write method, where you write the conditions and assertions. If you encounter an error, you throw some unchecked exception, like IllegalStateException, if everything is alright, you don't throw anything

like image 25
László Stahorszki Avatar answered Mar 18 '26 19:03

László Stahorszki