Im still fairly new to Rust and coming from almost exclusively Python development. Ive been trying to find a solution to this problem for a while now but Im also considering that I am approaching the problem in a way thats trying to be too python to work in Rust.
Say I have a struct “Person” as defined in one file:
// src/person.rs
pub struct Person {
pub age: i16,
}
impl Person {
pub fn get_older(&mut self, by_how_much: i16) {
self.age += by_how_much;
}
}
And in another file I have the struct Company:
// src/company.rs
use crate::person::Person;
pub struct Company {
pub ceo: Person
}
impl Company {
pub fn celebrate_ceos_birthday(&mut self) {
self.ceo.get_older(1);
}
}
In the Company file I would now like to write a unit-test to tests the behavior of the celebrate_ceos_birthday function:
// src/company.rs
#[test]
fn test_celebrate_ceos_birthday() {
let test_ceo = Person { age: 44 };
let mut test_company = Company { ceo: test_ceo };
test_company.celebrate_ceos_birthday();
assert_eq!(test_company.ceo.age, 45)
}
The problem that I have with this is that this test is now dependent also on the Person struct. To me that goes against the idea of a unit-test. In Python I could easily define a new “MockPerson” object inside the test (module) which simulates the interface of the real object as the Company object is using it. Of course due to the strict guidelines, if I try that in Rust, the compiler will tell me that its expecting a “Person” struct and not a “MockPerson”.
I have also tried around with using dynamic traits, but could not get it to work due to unknown size at compile time errors. I also looked into the mockall framework but havent found a way to use it for exactly what I want. Is there a recommended way to unit-test nested structs like this in Rust or do I need to abandon my ideas of how unit-tests should look?
Benedikt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.