Cześć. Próbuję przetestować jednostkowo metodę odpowiedzialną za pobieranie zawartości z pliku.
Przedtem operowałem na stworzonym przeze mnie pliku, ale problem się zaczął gdy potrzebowałem z końcem testu, by plik zresetować do 0.
Użyłem więc TemporaryFolder
.
Mam problem z dodaniem jakiejkolwiek zawartości do niej. Na googlach wyczytałem, że można to zrobić za pomocą FileWriter
, ale coś mi to nie działa. Cały czas mi wywala, że długość testedContent
to 0. Próbowałem używać flusha, ale nic to nie dawało.
Test:
package contentfile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.MockitoAnnotations;
import rankingsystem.RankingSystemService;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.junit.Assert.*;
public class ContentFileRetrieverServiceTest {
private ContentFileRetriever contentFileRetriever = new ContentFileRetrieverService();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setup() {
}
@Test
public void getContentFile() throws IOException {
File textFile = tempFolder.newFile("testText.txt");
String pathFile = textFile.getPath();
FileWriter fileWriter = new FileWriter(textFile);
fileWriter.write("Line1 a");
fileWriter.write("Line2 b c");
fileWriter.write("Line3 3");
String[] testedContent = contentFileRetriever.getContentFile(textFile.getAbsolutePath());
String[] expected = {"Line1 a", "Line2 b c", "Line 3"};
assertArrayEquals(expected, testedContent);
}
@Test(expected = IllegalArgumentException.class)
public void getContentFileWhenFileDoesNotExist() {
String pathFile = "unknown";
String[] testedContent = contentFileRetriever.getContentFile(pathFile);
}
}
Drugie pytanie, to czy kontent powinienem dodać w jakiś sposób w metodzie setup oraz czy muszę wywoływać metode deleteOnExit na obiekcie File
(wyczytałem, że ten TemporaryFolder sam się usuwa).