BAEL-3143 - made the required changes

This commit is contained in:
vatsalgosar
2019-10-23 00:17:07 +05:30
parent 9946fa53a1
commit a87822229a

View File

@@ -1,54 +1,34 @@
package com.baeldung.scanner; package com.baeldung.scanner;
import org.junit.Test; import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Scanner; import java.util.Scanner;
import static org.assertj.core.api.Assertions.fail; import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavaScannerUnitTest { public class JavaScannerUnitTest {
@Test @Test
public void whenReadingLines_thenCorrect() { public void whenReadingLines_thenCorrect() {
String input = "Scanner\nTest\n"; String input = "Scanner\nTest\n";
try (Scanner scanner = new Scanner(input)) {
byte[] byteArray = input.getBytes(StandardCharsets.UTF_8); assertEquals("Scanner", scanner.nextLine());
//@formatter:off assertEquals("Test", scanner.nextLine());
try (InputStream is = new ByteArrayInputStream(byteArray);
Scanner scanner = new Scanner(is)) {
//@formatter:on
String result = scanner.nextLine() + " " + scanner.nextLine();
String expected = input.replace("\n", " ")
.trim();
assertEquals(expected, result);
} catch (IOException e) {
fail(e.getMessage());
} }
} }
@Test(expected = NoSuchElementException.class) @Test(expected = NoSuchElementException.class)
public void whenReadingLinesFromStringContainingNoLines_thenThrowNoSuchElementException() { public void whenReadingLines_thenThrowNoSuchElementException() {
String input = ""; try (Scanner scanner = new Scanner("")) {
Scanner scanner = new Scanner(input); String result = scanner.nextLine();
String result = scanner.nextLine(); }
scanner.close();
} }
@Test(expected = IllegalStateException.class) @Test(expected = IllegalStateException.class)
public void whenReadingLinesUsingClosedScanner_thenThrowIllegalStateException() { public void whenReadingLines_thenThrowIllegalStateException() {
String input = ""; Scanner scanner = new Scanner("");
Scanner scanner = new Scanner(input);
scanner.close(); scanner.close();
String result = scanner.nextLine(); String result = scanner.nextLine();
} }
} }