How to write test cases for file related functions?

Let's say there is the following function.
And I want to write test cases for it. What is the best approach to write test cases?
Should I make a mock file data? Can I programmatically create mock data without creating the actual files?

use std::path::Path;

fn check_file_exist(path: &Path) -> bool {
    Path::new(path).exists()
}

Thanks

If you want to test actual filesystem access, then create a temporary directory and work inside that.

If you want to test writing/reading a file, then change your interfaces to generic so they work against arbitrary io::{Read, Write} types, and use slices, Vecs, io::Cursor etc. for storing data in memory without having to touch the physical file system at all.

4 Likes

Great, Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.