I am writing unit tests, and there is some code duplication I'd love to reduce. Here is my system under test:
#[derive(Debug, PartialEq)]
struct Fruit {
name: String,
weight: f32,
}
impl Fruit {
fn with_size_of(self: &Self, other: &Fruit)-> Fruit {
Fruit { name: self.name.clone(), weight: other.weight }
}
}
and these are two tests using the same two instances, an orange an an apple:
#[test]
fn apple_size_of_orange() {
let apple = Fruit {
name: String::from("Apple"),
weight: 2.0
};
let orange = Fruit {
name: String::from("Orange"),
weight: 3.0
};
assert_eq!(apple.with_size_of(&orange),
Fruit {
name: String::from("Apple"),
weight: 3.0
}
)
}
#[test]
fn orange_size_of_apple() {
let apple = Fruit {
name: String::from("Apple"),
weight: 2.0
};
let orange = Fruit {
name: String::from("Orange"),
weight: 3.0
};
assert_eq!(orange.with_size_of(&apple),
Fruit {
name: String::from("Orange"),
weight: 2.0
}
)
}
so I was wondering what is the idiomatic way to reuse these test values. Of course, we can have two functions like this:
fn apple() -> Fruit { Fruit {
name: String::from("Apple"),
weight: 2.0
}
}
but is there a more concise way? TIA!