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 import junit
.framework
.TestCase
;
26 public class CsvWriterTestCase
extends TestCase
{
27 public void testWrite() throws Exception
{
28 ByteArrayOutputStream out
= new ByteArrayOutputStream();
29 final CsvWriter csvWriter
= new CsvWriter(out
);
31 String
[] header
= { "Header1", "Header 2", "Header,3", "Header\n4",
33 String
[] line1
= { "Value1", "Value 2", "Value,3", "Value\n4",
35 csvWriter
.writeLine(Arrays
.asList(header
));
36 csvWriter
.writeLine(Arrays
.asList(line1
));
38 String reference
= "Header1,Header 2,\"Header,3\",\"Header\n4\",\"Header\"\"5\"\"\"\n"
39 + "Value1,Value 2,\"Value,3\",\"Value\n4\",\"Value\"\"5\"\"\"\n";
40 String written
= new String(out
.toByteArray());
41 assertEquals(reference
, written
);
43 System
.out
.println(written
);
45 final List
<String
> allTokens
= new ArrayList
<String
>();
46 CsvParser csvParser
= new CsvParser() {
47 protected void processLine(Integer lineNumber
, List
<String
> header
,
48 List
<String
> tokens
) {
50 allTokens
.addAll(header
);
51 allTokens
.addAll(tokens
);
54 ByteArrayInputStream in
= new ByteArrayInputStream(written
.getBytes());
57 List
<String
> allTokensRef
= new ArrayList
<String
>();
58 allTokensRef
.addAll(Arrays
.asList(header
));
59 allTokensRef
.addAll(Arrays
.asList(line1
));
61 assertEquals(allTokensRef
.size(), allTokens
.size());
62 for (int i
= 0; i
< allTokensRef
.size(); i
++)
63 assertEquals(allTokensRef
.get(i
), allTokens
.get(i
));