mercredi 23 août 2017

Good practice with Mockito And BufferedReader

I'm trying to test a class that make File/Stream treatement. For instance, the method readFile will use BufferedReader to return an ArrayList of String with every lines of the file inside.

public ArrayList<String> readFile(String fileName)
{
    ArrayList<String> result = new ArrayList<String>();
    FileReader fr = null;
    BufferedReader br = null;
    try {

        fr = new FileReader(STORAGE_DIRECTORY+fileName);
        br = new BufferedReader(fr);
        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            result.add(sCurrentLine);
        }
    }
        catch (FileNotFoundException e) {


            return new ArrayList<String>();
        } catch (IOException e) {

            return new ArrayList<String>();
        }

        br.close();
        fr.close();


        return result;
    }

But when I use mockito in order to mock bufferedReader method "readLine()",a FileNotFoundException is throwed because of FileReader constructor. Must I use temporaryFile or Mock FileReader constructor ?

@Test
public void readFileTest5() throws Exception {
    BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
    FileReader fileReader = Mockito.mock(FileReader.class);
    when(BufferedReader.readLine()).thenReturn("abc");
    assertEquals("",new ArrayList<String>(), FileUtil.readFile("abc"));
}

Thank you

Aucun commentaire:

Enregistrer un commentaire