View Javadoc
1   package com.opencsv;
2   
3   import com.opencsv.exceptions.CsvValidationException;
4   import org.junit.jupiter.api.*;
5   
6   import java.io.IOException;
7   import java.util.Locale;
8   import java.util.NoSuchElementException;
9   
10  import static org.junit.jupiter.api.Assertions.*;
11  import static org.mockito.Mockito.mock;
12  import static org.mockito.Mockito.when;
13  
14  public class CSVIteratorTest {
15      private static final String[] STRINGS = {"test1", "test2"};
16      private CSVIterator iterator;
17      private CSVReader mockReader;
18  
19      private static Locale systemLocale;
20  
21      @BeforeAll
22      public static void storeSystemLocale() {
23          systemLocale = Locale.getDefault();
24      }
25  
26      @AfterEach
27      public void setSystemLocaleBackToDefault() {
28          Locale.setDefault(systemLocale);
29      }
30  
31      @BeforeEach
32      public void setUp() throws IOException, CsvValidationException {
33          Locale.setDefault(Locale.US);
34          mockReader = mock(CSVReader.class);
35          when(mockReader.readNext()).thenReturn(STRINGS);
36          iterator = new CSVIterator(mockReader);
37      }
38  
39      @Test
40      public void readerExceptionCausesRunTimeException() throws IOException, CsvValidationException {
41          when(mockReader.readNext()).thenThrow(new IOException("reader threw test exception"));
42          Assertions.assertThrows(NoSuchElementException.class, () -> iterator.next());
43      }
44  
45      @Test
46      public void removeThrowsUnsupportedOperationException() {
47          String englishErrorMessage = null;
48          try {
49              iterator.remove();
50              fail("UnsupportedOperationException should have been thrown by read-only iterator.");
51          }
52          catch(UnsupportedOperationException e) {
53              englishErrorMessage = e.getLocalizedMessage();
54          }
55          
56          // Now with a different locale
57          iterator.setErrorLocale(Locale.GERMAN);
58          try {
59              iterator.remove();
60              fail("UnsupportedOperationException should have been thrown by read-only iterator.");
61          }
62          catch(UnsupportedOperationException e) {
63              assertNotSame(englishErrorMessage, e.getLocalizedMessage());
64          }
65      }
66  
67      @Test
68      public void initialReadReturnsStrings() {
69          assertArrayEquals(STRINGS, iterator.next());
70      }
71  
72      @Test
73      public void hasNextWorks() throws IOException, CsvValidationException {
74          when(mockReader.readNext()).thenReturn(null);
75          assertTrue(iterator.hasNext()); // initial read from constructor
76          iterator.next();
77          assertFalse(iterator.hasNext());
78      }
79  }