How to mock FileInputStream and other *Streams

前端 未结 5 2029
暖寄归人
暖寄归人 2021-01-14 11:47

I have class that gets GenericFile as input argument reads data and does some additional processing. I need to test it:

public class RealCardParser {

    pu         


        
5条回答
  •  忘掉有多难
    2021-01-14 12:10

    When you are having this question. You are probably not following dependency inversion principle correctly. You should use InputStream whenever it's possible. If your write your FileInputStream adapter method like this:

    class FileReader {
        public InputStream readAsStream() {
            return new FileInputStream("path/to/File.txt");
        }
    }
    

    Then you can mock the method to return ByteArrayInputStream alternatively. This is much easier to deal with, because you only need to pass a string to the stream instead of dealing with the specific FileInputStream implementation.

    If you are using mockito to mock, the sample goes like this:

    FileReader fd = mock(FileReader());
    String fileContent = ...;
    ByteArrayInputStream bais = new ByteArrayInputStream(fileContent);
    when(fd.readAsStream()).thenReturn(bais);
    

提交回复
热议问题