Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test private methods in Rust?

Tags:

testing

rust

How do I test private methods in Rust? I didn't find any information about it. There's no information in the documentation either.

like image 447
Incerteza Avatar asked Jan 16 '15 06:01

Incerteza


2 Answers

When using #[test], there’s nothing special about private or public methods—you’re just writing perfectly normal functions that can access anything they can access.

fn private_function() { }  #[test] fn test_private_function() {     private_function() } 

External tests, such as tests/*.rs and examples/*.rs if you’re using Cargo, or doc tests, do not get access to private members; nor should they: such tests are designed to be public API tests, not to be dealing with implementation details.

like image 184
Chris Morgan Avatar answered Sep 23 '22 21:09

Chris Morgan


I don't know if this issue is still open for you, but I found some documentation about it :

Test Organization

What I retained from it is that you can test private method but only if the test can see it (i.e. they are in the same scope), since tests follow the visibility rules as any other function.

Here is a working example :

pub fn add_two(a: i32) -> i32 {     internal_adder(a, 2) }  fn internal_adder(a: i32, b: i32) -> i32 {     a + b }  #[cfg(test)] mod tests {     use super::*;      #[test]     fn internal() {         assert_eq!(4, internal_adder(2, 2));     } } 

All in all, please remember that the debate wether private methods should or should not be tested is still open within the test community. Both sides have valid argument and the correct answer only relies on you, your vision on testing procedure and the context of your project.

like image 39
Senua Avatar answered Sep 22 '22 21:09

Senua