How to unit test a method that reads a given file

前端 未结 4 1155
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 23:55

I know this is a bit naive. How to unit test this piece of code without giving physical file as input. I am new to mockito and unit testing. So I am not sure. Please help.

4条回答
  •  旧时难觅i
    2021-01-02 00:29

    you could use combination of ByteArrayInputStream and BufferedReader class, to make your required file within your code. So there wouldn't be any need to create a real File on your system. What would happen if you don't have enough permission --based of some specific circumstances -- to create a file. On the code below, you create your own desirable content of your file:

    public static void main(String a[]){
    
        String str = "converting to input stream"+
                        "\n and this is second line";
        byte[] content = str.getBytes();
        InputStream is = null;
        BufferedReader bfReader = null;
        try {
            is = new ByteArrayInputStream(content);
            bfReader = new BufferedReader(new InputStreamReader(is));
            String temp = null;
            while((temp = bfReader.readLine()) != null){
                System.out.println(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(is != null) is.close();
            } catch (Exception ex){
    
            }
        }
    
    }
    

提交回复
热议问题