1 package au.com.bytecode.opencsv.bean; 2 3 import au.com.bytecode.opencsv.CSVReader; 4 import au.com.bytecode.opencsv.CSVWriter; 5 import org.junit.Assert; 6 import org.junit.Before; 7 import org.junit.Test; 8 9 import java.beans.IntrospectionException; 10 import java.beans.PropertyDescriptor; 11 import java.io.IOException; 12 import java.io.StringWriter; 13 import java.util.ArrayList; 14 import java.util.List; 15 16 public class BeanToCsvTest { 17 18 private static final String TEST_STRING = "\"name\",\"orderNumber\",\"num\"\n" 19 + "\"kyle\",\"abc123456\",\"123\"\n" 20 + "\"jimmy\",\"def098765\",\"456\"\n"; 21 22 private List<MockBean> testData; 23 private BeanToCsv<MockBean> bean; 24 25 @Before 26 public void setUp() { 27 bean = new BeanToCsv<MockBean>(); 28 29 testData = new ArrayList<MockBean>(); 30 MockBean mb = new MockBean(); 31 mb.setName("kyle"); 32 mb.setOrderNumber("abc123456"); 33 mb.setNum(123); 34 testData.add(mb); 35 mb = new MockBean(); 36 mb.setName("jimmy"); 37 mb.setOrderNumber("def098765"); 38 mb.setNum(456); 39 testData.add(mb); 40 } 41 42 private MappingStrategy createErrorMappingStrategy() { 43 return new MappingStrategy() { 44 45 public PropertyDescriptor findDescriptor(int col) 46 throws IntrospectionException { 47 throw new IntrospectionException("This is the test exception"); 48 } 49 50 public Object createBean() throws InstantiationException, 51 IllegalAccessException { 52 return null; 53 } 54 55 public void captureHeader(CSVReader reader) throws IOException { 56 } 57 }; 58 } 59 60 @Test(expected = RuntimeException.class) 61 public void throwRuntimeExceptionWhenExceptionIsThrown() { 62 StringWriter sw = new StringWriter(); 63 CSVWriter writer = new CSVWriter(sw); 64 bean.write(createErrorMappingStrategy(), writer, testData); 65 } 66 67 @Test 68 public void testWriteQuotes() throws IOException { 69 ColumnPositionMappingStrategy<MockBean> strat = new ColumnPositionMappingStrategy<MockBean>(); 70 strat.setType(MockBean.class); 71 String[] columns = new String[]{"name", "orderNumber", "num"}; 72 strat.setColumnMapping(columns); 73 74 StringWriter sw = new StringWriter(); 75 76 boolean value = bean.write(strat, sw, testData); 77 78 Assert.assertTrue(value); 79 80 String content = sw.getBuffer().toString(); 81 Assert.assertNotNull(content); 82 Assert.assertEquals(TEST_STRING, content); 83 } 84 }