|
| 1 | +package com.baeldung.filewriter; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.nio.file.Files; |
| 5 | +import java.nio.file.Path; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Random; |
| 9 | +import java.util.stream.IntStream; |
| 10 | + |
| 11 | +import org.junit.After; |
| 12 | +import org.junit.Assert; |
| 13 | +import org.junit.Test; |
| 14 | + |
| 15 | +public class FileWriterExampleUnitTest { |
| 16 | + |
| 17 | + private static final String FILE_NAME = "src/test/resources/FileWriterTest.txt"; |
| 18 | + private static final String STRING_TO_WRITE = "Hello Folks!"; |
| 19 | + private static final String STRING_TO_APPEND = "Hello Folks Again!"; |
| 20 | + private static final char[] CHAR_ARRAY_TO_WRITE = STRING_TO_WRITE.toCharArray(); |
| 21 | + |
| 22 | + private FileWriterExample fileWriterExample = new FileWriterExample(); |
| 23 | + |
| 24 | + @After |
| 25 | + public void tearDown() throws IOException { |
| 26 | + Files.delete(Path.of(FILE_NAME)); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void testWriteString() throws IOException { |
| 31 | + fileWriterExample.writeString(FILE_NAME, STRING_TO_WRITE); |
| 32 | + Assert.assertEquals(STRING_TO_WRITE, new String(Files.readAllBytes(Path.of(FILE_NAME)))); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void testAppendString() throws IOException { |
| 37 | + fileWriterExample.writeString(FILE_NAME, STRING_TO_WRITE); |
| 38 | + fileWriterExample.appendString(FILE_NAME, STRING_TO_APPEND); |
| 39 | + Assert.assertEquals(STRING_TO_WRITE + STRING_TO_APPEND, new String(Files.readAllBytes(Path.of(FILE_NAME)))); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void testWriteCharArray() throws IOException { |
| 44 | + fileWriterExample.writeCharArray(FILE_NAME, CHAR_ARRAY_TO_WRITE); |
| 45 | + Assert.assertEquals(STRING_TO_WRITE, new String(Files.readAllBytes(Path.of(FILE_NAME)))); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void testWriteWithBufferedWriter() throws IOException{ |
| 50 | + final List<String> stringsToWrite = new ArrayList<>(); |
| 51 | + for(int i=0 ; i < 10000;i++) { |
| 52 | + stringsToWrite.add("Random string "+i); |
| 53 | + } |
| 54 | + fileWriterExample.writeWithBufferedWriter(FILE_NAME, stringsToWrite); |
| 55 | + Assert.assertNotNull(new String(Files.readAllBytes(Path.of(FILE_NAME)))); |
| 56 | + } |
| 57 | +} |
0 commit comments