Testing private functions

Hello

In the Rust documentation about testing it's advised to make a separate module for testing.
So I did that:

mod lol {
    pub fn func_a() -> u8 {
        func_b()
    }
    
    
    fn func_b() -> u8 {
        1
    }
}

fn main() {
    println!("{}", lol::func_a());
}


#[cfg(test)]
mod tests {
    use super::lol::*;
    
    // Works
    #[test]
    fn test_a() {
        assert_eq!(func_a(), 1);
    }
    
    //Doesn't work cause private
    #[test]
    fn test_b() {
        assert_eq!(func_b(), 1);
    }
}

Playground.

But this doesn't work because I can't access the private functions I want to test. Because I have a lot of complex private functions, I'd like to test those as well.

What is the best and most idiomatic way to do this? Just writing test-functions in the module lol for the private functions? Or using documentation test? I by the way have the weird scenario that in my real code the documentation tests do not get executed when running cargo test.

Thanks.

Usually, each module has its own tests submodule, which has access to the private functions of its parent module. For example, the regex crate has tests for the dfa module here and tests for the expand module here.

Documentation tests are only run on public functions, since each documentation test is compiled as a separate binary that links to your library and can call its public API.

1 Like

Alright!

This works.

mod lol {
    pub fn func_a() -> u8 {
        func_b()
    }
    
    
    fn func_b() -> u8 {
        1
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
        
        // Works
        #[test]
        fn test_a() {
            assert_eq!(func_a(), 1);
        }
        
        //Doesn't work cause private (WORKS NOW!)
        #[test]
        fn test_b() {
            assert_eq!(func_b(), 1);
        }
    }
}

fn main() {
    println!("{}", lol::func_a());
}