I am working on improving code coverage of my project and since there is a method I wrote to write file into android internalStorage
by using the following code snippet from Android Developer website.
String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
My idea is to assert by reading the file and compare with hello world!
and see if they matches to prove that my writing function works in unit test/ Android Instrumentation test. However, it not really straightforward for me to test this because of following
What is the best practice to test this kind of IO functionality in Android? Should I even care about if the file had been created and put? Or I should simply just check if the fos
from in not null?
FileOutputStream fos =new FileOutputStream(file);
Please kindly provide me the advices. Thanks.
I wouldn't test that the file is saved - this is not your system and Android AOSP should have tests for making sure the file actually saves. Read more here
What you want to test is if you are telling Android to save your file. Perhaps like this:
String FILENAME = "hello_file";
String string = "hello world!";
File testFile = new File(context.getFilesDir(), FILENAME);
FileOutputStream fos =new FileOutputStream(file);
public void saveAndClose(String data, FileOutputStream fos) {
fos.write(data.getBytes());
fos.close();
}
Then your test would use Mockito for the FOS and be:
FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure written";
classUnderTest.saveAndClose(data, mockFos);
verify(mockFos).write(data.getBytes());
second test:
FileOutputStream mockFos = Mockito.mock(FileOutputStream.class);
String data = "ensure closed";
classUnderTest.saveAndClose(data, mockFos);
verify(mockFos).close();