|
1 | 1 | package com.baeldung.scanner; |
2 | 2 |
|
3 | | -import org.junit.Test; |
| 3 | +import static org.junit.Assert.assertEquals; |
4 | 4 |
|
5 | | -import java.io.ByteArrayInputStream; |
6 | | -import java.io.IOException; |
7 | | -import java.io.InputStream; |
8 | | -import java.nio.charset.StandardCharsets; |
9 | 5 | import java.util.NoSuchElementException; |
10 | 6 | import java.util.Scanner; |
11 | 7 |
|
12 | | -import static org.assertj.core.api.Assertions.fail; |
13 | | -import static org.junit.Assert.assertEquals; |
| 8 | +import org.junit.Test; |
14 | 9 |
|
15 | 10 | public class JavaScannerUnitTest { |
16 | 11 |
|
17 | 12 | @Test |
18 | 13 | public void whenReadingLines_thenCorrect() { |
19 | 14 | 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()); |
| 15 | + try (Scanner scanner = new Scanner(input)) { |
| 16 | + assertEquals("Scanner", scanner.nextLine()); |
| 17 | + assertEquals("Test", scanner.nextLine()); |
34 | 18 | } |
35 | 19 | } |
36 | 20 |
|
37 | 21 | @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(); |
| 22 | + public void whenReadingLines_thenThrowNoSuchElementException() { |
| 23 | + try (Scanner scanner = new Scanner("")) { |
| 24 | + String result = scanner.nextLine(); |
| 25 | + } |
43 | 26 | } |
44 | 27 |
|
45 | 28 | @Test(expected = IllegalStateException.class) |
46 | | - public void whenReadingLinesUsingClosedScanner_thenThrowIllegalStateException() { |
47 | | - String input = ""; |
48 | | - Scanner scanner = new Scanner(input); |
| 29 | + public void whenReadingLines_thenThrowIllegalStateException() { |
| 30 | + Scanner scanner = new Scanner(""); |
49 | 31 | scanner.close(); |
50 | 32 | String result = scanner.nextLine(); |
51 | 33 | } |
52 | | - |
53 | | - |
54 | 34 | } |
0 commit comments