I spend last few days trying to get a solid grasp of android testing. Its hard to find good explanations/full examples. Could anyone help me with writing simple test to the class below? I know how to make an instrumental test for such class, but I believe that it could be easily tested using Mockito and Junit.
public class Storage {
private final static String FILENAME = "data_storage.txt";
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static String readDataFromFile(File file) {
FileInputStream fis = null;
final StringBuilder storedString = new StringBuilder();
try {
fis = new FileInputStream(file);
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = dataIO.readLine()) != null) {
storedString.append(strLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return storedString.toString();
}
public static void saveDataToFile(String data, File file) {
FileOutputStream fileOutput = null;
try {
fileOutput = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutput);
outputStreamWriter.write(data);
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveData(Context context, String data) {
File file = null;
if (isExternalStorageWritable())
file = new File(Environment.getExternalStorageDirectory(), FILENAME);
else
file = new File(context.getCacheDir(), FILENAME);
saveDataToFile(data, file);
}
public static String readData(Context context) {
File file = null;
if (isExternalStorageWritable())
file = new File(Environment.getExternalStorageDirectory(), FILENAME);
else
file = new File(context.getCacheDir(), FILENAME);
return readDataFromFile(file);
}
}
here is an example of what I tried to do:
public class StorageTest {
File file = Mockito.mock(File.class);
@Mock Context mockContext;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(file.getPath()).thenReturn("/tmp/");
}
@Test
public void shouldWriteData()
{
assertNotNull(file);
String data = "mockito data test";
Storage.saveDataToFile(data,file);
}
}
that line
fileOutput = new FileOutputStream(file);
throws a null pointer exception. How should I mock that kind of code, how should I mock files and input/output streams? IS it possible to test it using Junit, or only instrumental tests?
Cheers guys