Dependency injection for file


In chapter 12 of the Rust book v2 we have the following code:

pub fn run(config: Config) -> Result<(), Box<Error>> {
    let mut f = File::open(config.filename)?;

    let mut contents = String::new();
    f.read_to_string(&mut contents)?;

    println!("With text:\n{}", contents);


How do we write tests for this function? Can I use dependency injection for the file object and if so how do I do that?


To mock it, you would have to create a trait—because File::open is a method of the concrete type, not of any trait—and make the function generic in that trait. And than such test would test exactly nothing. Because it would test that the function calls the two methods in a way your mock expect, which tells you absolutely nothing about whether it calls them in the way the actual File expects!

So instead simply write a file out and read it back. Much simpler, but also more representative.


Also you need to ask yourself the question “what am I testing here?”. Cause i feel like you are just testing rust classes (which work fine)


creata a simple file handly


I understand where you are going but what you propose in your last sentence is more an integration test then a unit test.

Working with traits is indeed something I can do. Thanks.


What do you mean with “just testing rust classes”. There are no classes in Rust.


Ah my bad. Been in OOP for too long :joy: by classes i didn’t mean “concrete” classes but just an encapsulation of code like a struct.


Yes, it is. Because integration tests are the ones you should have. Because they are the only ones that actually tell you that your code is working. Unit tests don’t.

Unit tests are a great debugging tool, but as you make the granularity finer, the cost of writing the tests increases and the return decreases. Writing a unit test for a 5-line function with trivial cyclomatic complexity is way beyond the point of any useful efficiency.