|
| 1 | +package com.baeldung.scanner; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.io.ByteArrayInputStream; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStream; |
| 8 | +import java.nio.charset.StandardCharsets; |
| 9 | +import java.util.NoSuchElementException; |
| 10 | +import java.util.Scanner; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.fail; |
| 13 | +import static org.junit.Assert.assertEquals; |
| 14 | + |
| 15 | +public class JavaScannerUnitTest { |
| 16 | + |
| 17 | + @Test |
| 18 | + public void whenReadingLines_thenCorrect() { |
| 19 | + String input = "Scanner\nTest\n"; |
| 20 | + |
| 21 | + byte[] byteArray = input.getBytes(StandardCharsets.UTF_8); |
| 22 | + //@formatter:off |
| 23 | + try (InputStream is = new ByteArrayInputStream(byteArray); |
| 24 | + Scanner scanner = new Scanner(is)) { |
| 25 | + |
| 26 | + //@formatter:on |
| 27 | + String result = scanner.nextLine() + " " + scanner.nextLine(); |
| 28 | + |
| 29 | + String expected = input.replace("\n", " ") |
| 30 | + .trim(); |
| 31 | + assertEquals(expected, result); |
| 32 | + } catch (IOException e) { |
| 33 | + fail(e.getMessage()); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + @Test(expected = NoSuchElementException.class) |
| 38 | + public void whenReadingLinesFromStringContainingNoLines_thenThrowNoSuchElementException() { |
| 39 | + String input = ""; |
| 40 | + Scanner scanner = new Scanner(input); |
| 41 | + String result = scanner.nextLine(); |
| 42 | + scanner.close(); |
| 43 | + } |
| 44 | + |
| 45 | + @Test(expected = IllegalStateException.class) |
| 46 | + public void whenReadingLinesUsingClosedScanner_thenThrowIllegalStateException() { |
| 47 | + String input = ""; |
| 48 | + Scanner scanner = new Scanner(input); |
| 49 | + scanner.close(); |
| 50 | + String result = scanner.nextLine(); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | +} |
0 commit comments