2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.util
;
18 import java
.io
.ByteArrayInputStream
;
19 import java
.io
.ByteArrayOutputStream
;
20 import java
.util
.ArrayList
;
21 import java
.util
.Arrays
;
22 import java
.util
.List
;
24 /** {@link CsvWriter} tests. */
25 public class CsvWriterTest
{
26 public void testWrite() throws Exception
{
27 ByteArrayOutputStream out
= new ByteArrayOutputStream();
28 final CsvWriter csvWriter
= new CsvWriter(out
);
30 String
[] header
= { "Header1", "Header 2", "Header,3", "Header\n4", "Header\"5\"" };
31 String
[] line1
= { "Value1", "Value 2", "Value,3", "Value\n4", "Value\"5\"" };
32 csvWriter
.writeLine(Arrays
.asList(header
));
33 csvWriter
.writeLine(Arrays
.asList(line1
));
35 String reference
= "Header1,Header 2,\"Header,3\",\"Header\n4\",\"Header\"\"5\"\"\"\n"
36 + "Value1,Value 2,\"Value,3\",\"Value\n4\",\"Value\"\"5\"\"\"\n";
37 String written
= new String(out
.toByteArray());
38 assert reference
.equals(written
);
40 System
.out
.println(written
);
42 final List
<String
> allTokens
= new ArrayList
<String
>();
43 CsvParser csvParser
= new CsvParser() {
44 protected void processLine(Integer lineNumber
, List
<String
> header
, List
<String
> tokens
) {
46 allTokens
.addAll(header
);
47 allTokens
.addAll(tokens
);
50 ByteArrayInputStream in
= new ByteArrayInputStream(written
.getBytes());
53 List
<String
> allTokensRef
= new ArrayList
<String
>();
54 allTokensRef
.addAll(Arrays
.asList(header
));
55 allTokensRef
.addAll(Arrays
.asList(line1
));
57 assert allTokensRef
.size() == allTokens
.size();
58 for (int i
= 0; i
< allTokensRef
.size(); i
++)
59 assert allTokensRef
.get(i
).equals(allTokens
.get(i
));