4

I'm writing a library which contains private structs and methods:

/// Constructs a new `Object`
///
/// Internal API
///
/// # Example
/// ```rust
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```

When I run cargo test, the doctest fails because Object is a private struct.

Is it possible to make it compile and run?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Alex
  • 9,891
  • 11
  • 53
  • 87

2 Answers2

0

I don't think it is possible if you want the test to compile and run, see this related question.

I you only want to include the code as a sample in the documentation, without trying to compile and run it, you can exclude it from the tests by adding the ignore flag:

/// ```rust,ignore
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```
Jmb
  • 18,893
  • 2
  • 28
  • 55
0

As mentioned by @Jmb in other answer, No, it is not possible. But instead of ignoring the code portion, we can unit test it.

However, we can unit test private methods and structs. cargo test will test both doctests and unittests, so we can rely on it. I'm sure there's some way to include coverage of unittests to doctests or all tests metric (e.g., in Sonar).

Here's an example on how can unit test lib::object::Object:

#[cfg(test)]
mod tests {
    use super::*; // imports all the items from the parent module, including our private Object struct

    #[test]
    fn test_object_new() {
        let tn = Object::new();
        // Add assertions here to test the `Object` struct.
    }
}
Jishan Shaikh
  • 1,572
  • 2
  • 13
  • 31