|
| 1 | +package com.baeldung.commons.csv; |
| 2 | + |
| 3 | +import org.apache.commons.csv.CSVFormat; |
| 4 | +import org.apache.commons.csv.CSVPrinter; |
| 5 | +import org.apache.commons.csv.CSVRecord; |
| 6 | +import org.junit.Test; |
| 7 | + |
| 8 | +import java.io.FileReader; |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.Reader; |
| 11 | +import java.io.StringWriter; |
| 12 | +import java.util.Collections; |
| 13 | +import java.util.LinkedHashMap; |
| 14 | +import java.util.Map; |
| 15 | + |
| 16 | +import static org.junit.Assert.assertEquals; |
| 17 | + |
| 18 | +public class CSVReaderWriterTest { |
| 19 | + |
| 20 | + public static final Map<String, String> AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap<String, String>() { |
| 21 | + { |
| 22 | + put("Dan Simmons", "Hyperion"); |
| 23 | + put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy"); |
| 24 | + } |
| 25 | + }); |
| 26 | + public static final String[] HEADERS = { "author", "title" }; |
| 27 | + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; |
| 28 | + |
| 29 | + @Test |
| 30 | + public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { |
| 31 | + Reader in = new FileReader("src/test/resources/book.csv"); |
| 32 | + Iterable<CSVRecord> records = CSVFormat.DEFAULT |
| 33 | + .withHeader(HEADERS) |
| 34 | + .withFirstRecordAsHeader() |
| 35 | + .parse(in); |
| 36 | + for (CSVRecord record : records) { |
| 37 | + String author = record.get("author"); |
| 38 | + String title = record.get("title"); |
| 39 | + assertEquals(AUTHOR_BOOK_MAP.get(author), title); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { |
| 45 | + StringWriter sw = new StringWriter(); |
| 46 | + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { |
| 47 | + AUTHOR_BOOK_MAP.forEach((author, title) -> { |
| 48 | + try { |
| 49 | + printer.printRecord(author, title); |
| 50 | + } catch (IOException e) { |
| 51 | + e.printStackTrace(); |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + assertEquals(EXPECTED_FILESTREAM, sw |
| 56 | + .toString() |
| 57 | + .trim()); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments