|
| 1 | +package com.baeldung.csv.reader |
| 2 | + |
| 3 | +import org.scalatest.matchers.should |
| 4 | +import org.scalatest.wordspec.AnyWordSpec |
| 5 | + |
| 6 | +import java.io.{File, PrintWriter} |
| 7 | +import java.nio.file.{Files, Path} |
| 8 | +import java.util.UUID |
| 9 | + |
| 10 | +class ScalaCSVReadersUnitTest extends AnyWordSpec with should.Matchers { |
| 11 | + |
| 12 | + "SimpleCSVReader" should { |
| 13 | + "read a csv file" in { |
| 14 | + commonTestBody(new SimpleCSVReader, randomTmpFile().toFile) |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + "ScalaCSVReader" should { |
| 19 | + "read a csv file" in { |
| 20 | + commonTestBody(new ScalaCSVReader, randomTmpFile().toFile) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + "OpenCSVReader" should { |
| 25 | + "read a csv file" in { |
| 26 | + commonTestBody(new OpenCSVReader, randomTmpFile().toFile) |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + "ApacheCommonsCSVReader" should { |
| 31 | + "read a csv file" in { |
| 32 | + commonTestBody(new ApacheCommonsCSVReader, randomTmpFile().toFile) |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private def commonTestBody( |
| 37 | + testee: CommaSeparatedValuesReader, |
| 38 | + file: File |
| 39 | + ): Unit = { |
| 40 | + val result = testee.read(file) |
| 41 | + assert(result.headers === List("column1", "column2")) |
| 42 | + assert( |
| 43 | + result.rows === List( |
| 44 | + List("1.1", "1.2"), |
| 45 | + List("2.1", "2.2") |
| 46 | + ) |
| 47 | + ) |
| 48 | + } |
| 49 | + |
| 50 | + private def randomTmpFile(): Path = { |
| 51 | + val path = Files.createTempFile( |
| 52 | + s"persons-${UUID.randomUUID().toString.take(8)}", |
| 53 | + "csv" |
| 54 | + ) |
| 55 | + val writer = new PrintWriter(path.toFile) |
| 56 | + writer.println(List("column1", "column2").mkString(",")) |
| 57 | + writer.println(List("1.1", "1.2").mkString(",")) |
| 58 | + writer.println(List("2.1", "2.2").mkString(",")) |
| 59 | + writer.close() |
| 60 | + path |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments