Skip to content

Commit

Permalink
Added some tests for CsvPrinter.java
Browse files Browse the repository at this point in the history
  • Loading branch information
TwoOfTwelve committed Nov 18, 2023
1 parent b8f061b commit 0e726b7
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 3 deletions.
26 changes: 23 additions & 3 deletions core/src/main/java/de/jplag/reporting/csv/CsvPrinter.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package de.jplag.reporting.csv;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -79,11 +81,29 @@ public void setLineEnd(String lineEnd) {
*/
public void printToFile(File file) throws IOException {
try (Writer writer = FileUtils.openFileWriter(file)) {
this.writeTitleRow(writer);
this.printCsv(writer);
}
}

public String printToString() throws IOException {
String csv;

for (String[] datum : this.data) {
this.printRow(writer, datum);
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
try (Writer writer = new OutputStreamWriter(outputStream)) {
this.printCsv(writer);
}

csv = outputStream.toString();
}

return csv;
}

private void printCsv(Writer writer) throws IOException {
this.writeTitleRow(writer);

for (String[] datum : this.data) {
this.printRow(writer, datum);
}
}

Expand Down
35 changes: 35 additions & 0 deletions core/src/test/java/de/jplag/reporting/csv/CsvPrinterTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package de.jplag.reporting.csv;

import java.io.IOException;
import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class CsvPrinterTest {
private static final String EXPECTED_CSV_TEXT = "1,test1\r\n2,\"test2,\"\"x\"\"\"\r\n";
private static final List<CsvTestItem> TEST_ITEMS = List.of(new CsvTestItem(1, "test1"), new CsvTestItem(2, "test2,\"x\""));

@Test
void testPrintWithReflectiveMapper() throws IOException {
CsvDataMapper<CsvTestItem> mapper = new ReflectiveCsvDataMapper<>(CsvTestItem.class);
CsvPrinter<CsvTestItem> printer = new CsvPrinter<>(mapper);

printer.addRows(TEST_ITEMS);

Assertions.assertEquals(EXPECTED_CSV_TEXT, printer.printToString());
}

@Test
void testPrintWithHardcodedMapper() throws IOException {
CsvDataMapper<CsvTestItem> mapper = new HardcodedCsvDataMapper<>(2, item -> new Object[] {item.number(), item.text()});
CsvPrinter<CsvTestItem> printer = new CsvPrinter<>(mapper);

printer.addRows(TEST_ITEMS);

Assertions.assertEquals(EXPECTED_CSV_TEXT, printer.printToString());
}

private record CsvTestItem(@CsvValue(1) int number, @CsvValue(2) String text) {
}
}

0 comments on commit 0e726b7

Please sign in to comment.