#How To Dynamically Inject Mocks In Tests?

10 messages · Page 1 of 1 (latest)

quick summit
#

What I'm gathering is that I don't think that's how it works. It kinda looks like making a trait is the only easy path forward.

chrome olive
#

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.

errant panther
#

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

errant panther
#

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

fair cove
#

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)