Skip to content

Commit 9946fa5

Browse files
committed
BAEL-3143 - nextLine() method of java.util.Scanner class
1 parent 9d5c7d0 commit 9946fa5

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)