#How To Dynamically Inject Mocks In Tests?
10 messages · Page 1 of 1 (latest)
I believe that to mock you need dynamic dispatch to be able to “slide in” another implement in for testing. See https://doc.rust-lang.org/book/ch17-02-trait-objects.html for information.
I would suggest that the more standard way of structuring code to be testable doesn’t use mocks like this often. The whole point of an enumeration is that you guarantee that all cases are covered.
Usually if you need this you'd make your code generic
It doesn't need to use trait objects, just regular generics
The tests fill the generic with a mock, the real code with a real implementation
It is.
If you come from a language with inheritance and/or interfaces, think of a trait like an interface.
You need one to be able to swap out the actual implementation
Hi, wanted to ask a question about testing and mocking
if I have the following data
enum Animal {
Cow,
Sheep
}
impl Animal {
fn print(&self) -> String {
match *self {
Animal::Cow => "Cow".to_string(),
Animal::Sheep => "Sheep".to_string(),
}
}
}
fn print_cow() {
Animal::Cow.print();
}
Is there anyway possible where I can mock the return value of Animal::Cow.print(); **WITHOUT **having to make a trait object , passing it into the print_cow function and using the crate mockall ? (https://docs.rs/mockall/0.11.1/mockall/#getting-started I basically want to achieve this example without having to pass in a trait object into the method)
A powerful mock object library for Rust.