Using TDD to develop file traversing code in Java

前端 未结 2 1197
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 06:05

I had to implement some code to traverse a directory structure and return a list of files found. The requirements were pretty simple:

  1. Given a base directory, f
2条回答
  •  醉梦人生
    2021-01-19 06:40

    As someone who gets very antsy about unit tests that take longer than a few milliseconds to complete, I strongly recommend mocking out the file I/O.

    However, I don't think you should mock the File class directly. Instead, look at your use of the File class as the "how", and try to identify the "what". Then codify that with an interface.

    For example: you mentioned that one of the things you do is intercept calls to File.isDirectory. Instead of interacting with the File class, what if your code interacted with some implementation of an interface like:

    public interface FileSystemNavigator {
        public boolean isDirectory(String path);
    
        // ... other relevant methods
    }
    

    This hides the use of File.isDirectory from the rest of your code, while simultaneously reframing the problem into something more relevant to your program.

提交回复
热议问题