I have two structs implementing the same trait using a different algorithm. I want to write the unit tests once and run them against both structs. What is the best way to do this?
My concern is to test both implementations as black box and avoid code duplication as much as possible.
[rust newbie] Here is a non compilable source code to show what I tried. I am not interested in dynamic dispatching - The production code will use just one of the implementations.
pub trait Searchable<T> {
fn search(&self, item: &T, radius: f32) -> Vec<T>;
}
struct Item { x: u32, y: u32}
struct A { some_field: u32 }
impl Searchable<Item> for A {
fn search(&self, _item: &Item, _radius: f32) -> Vec<Item> { vec![] }
}
struct B {}
impl Searchable<Item> for B {
fn search(&self, _item: &Item, _radius: f32) -> Vec<Item> { vec![] }
}
#[cfg(test)]
mod tests {
use super::*;
/// Create a new Searchable and a vector of Items.
/// The Searchable will be either A or B, depending on the value of use_a.
fn setup<T>(use_a: bool) -> (dyn Searchable<T>, Vec<Item>) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
// generate some data
(if use_a {A{}} else {B{}}, Vec::new())
}
#[test]
fn which_search() {
let (mut store, items) = setup(true);
// do some searches and assertions
}
}
fn main() {} // to sooth the compiler
Tried changing the code to be able to do dynamic dispatching (just for the test), but did not succeed.