In another larger project I have lots of helper functions and trait definitions for my tests. I want to use these both when I test the public interface of the library and when I test private functions.
Right now I am trying to use workspaces to achieve this but without success. This is the project structure of my minified example:
.
├── Cargo.lock
├── Cargo.toml
├── mylibrary
│ ├── Cargo.toml
│ ├── src
│ │ └── lib.rs
│ └── tests
│ └── alltests.rs
└── testutil
├── Cargo.toml
└── src
└── lib.rs
And the file contents:
//testutil/src/lib.rs
use mylibrary;
pub fn add_custom(x: i32, y: i32) -> mylibrary::Custom {
mylibrary::add(mylibrary::mk_custom(x), mylibrary::mk_custom(y))
}
// mylibrary/tests/alltests.rs
use mylibrary;
use testutil;
#[test]
fn adds_correctly() {
assert_eq!(testutil::add_custom(2, 3).value, 5)
}
// mylibrary/src/lib.rs
#[cfg(test)]
use testutil;
pub struct Custom {
private_field: i32,
pub value: i32,
}
pub fn mk_custom(v: i32) -> Custom {
Custom { private_field: v, value: v }
}
pub fn add(x: Custom, y: Custom) -> Custom {
let result = x.value + y.value;
Custom { private_field: result, value: result }
}
#[test] // this test successfully accesses the private field
fn private_field_test_1() {
let result = add(mk_custom(2), mk_custom(3));
assert_eq!(result.value, result.private_field)
}
#[test]
fn private_field_test_2() {
let result = testutil::add_custom(2, 3);
assert_eq!(result.value, result.private_field) // <-- error
}
> cargo test
...
error[E0616]: field `private_field` of struct `mylibrary::Custom` is private
--> mylibrary/src/lib.rs:28:37
|
28 | assert_eq!(result.value, result.private_field)
| ^^^^^^^^^^^^^ private field
...
I understand that I'm going through the public interface when I use this helper function which prevents me from reading the private field. Unfortunately the only solution I can come up with on my own is to copy and paste the helper code which isn't ideal.
question from:
https://stackoverflow.com/questions/65910349/share-code-between-integration-tests-and-in-line-tests-in-rust 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…