View Javadoc
1   package com.opencsv;
2   /*
3    Copyright 2005 Bytecode Pty Ltd.
4   
5    Licensed under the Apache License, Version 2.0 (the "License");
6    you may not use this file except in compliance with the License.
7    You may obtain a copy of the License at
8   
9    http://www.apache.org/licenses/LICENSE-2.0
10  
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16   */
17  
18  import com.opencsv.exceptions.CsvValidationException;
19  import org.junit.jupiter.api.BeforeEach;
20  import org.junit.jupiter.api.Test;
21  
22  import java.io.File;
23  import java.io.FileReader;
24  import java.io.FileWriter;
25  import java.io.IOException;
26  
27  import static org.junit.jupiter.api.Assertions.assertEquals;
28  
29  public class OpencsvTest {
30  
31     private File tempFile = null;
32  
33      @BeforeEach
34     public void setUp() throws IOException {
35        tempFile = File.createTempFile("csvWriterTest", ".csv");
36        tempFile.deleteOnExit();
37     }
38  
39     /**
40      * Test the full cycle of write-read
41      * @throws IOException But not really
42      */
43     @Test
44     public void testWriteRead() throws IOException, CsvValidationException {
45        final String[][] data = new String[][]{{"hello, a test", "one nested \" test"}, {"\"\"", "test", null, "8"}};
46  
47        ICSVWriter writer = new CSVWriter(new FileWriter(tempFile));
48        for (String[] aData : data) {
49           writer.writeNext(aData);
50        }
51        writer.close();
52  
53        CSVReader reader = new CSVReader(new FileReader(tempFile));
54  
55        String[] line;
56        for (int row = 0; (line = reader.readNext()) != null; row++) {
57           assertEquals(line.length, data[row].length);
58  
59           for (int col = 0; col < line.length; col++) {
60              if (data[row][col] == null) {
61                 assertEquals("", line[col]);
62              } else {
63                 assertEquals(line[col], data[row][col]);
64              }
65           }
66        }
67        reader.close();
68     }
69  }