Can modules have fields?

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!

You can create statics or consts anywhere an item can go, including at the top level in a module. I wouldn't worry about it, though, especially in a test.

3 Likes

Probably you're already having the best approach with the function. There's constants too, but those do not (yet) support allocations as in Strings. There's also lazy static values, but that's even slightly less concise than that apple function, and you might need to add a dependency for a Lazy type.

4 Likes

A simple slightly more concise way could be to have a single such function that returns (Fruit, Fruit).

1 Like

How about rstest fixtures?

this is cool, although just a little bit verbose. thanks for sharing

Nice to know, thank you.