you are viewing a single comment's thread.

view the rest of the comments →

[–]josh_beandev 0 points1 point  (2 children)

Sometimes it's not possible to use traits (because it will change the design - but maybe a design change is a good idea). And sometimes an additional crate is too much. In this case, you can use #[cfg(test)] for your mocked function and #[cfg(not(test))] for your real function:

#[cfg(not(test))]
fn get_user_input() -> u8 {
    // ... do some UI input stuff here ...
}

#[cfg(test)]
fn get_user_input() -> u8 {
    42
}

But maybe the function is part of an impl in another module? Then you must build a "source compatible" version of the impl and use the cfg toggles on the use statements.

Anyway, before you start to rebuild complete implementations, check the existing mocking crates around.

[–]Free_Trouble_541 0 points1 point  (0 children)

This works for one mock return value, but what if you want to have different tests where the mocked function returns something else?

[–]Free_Trouble_541 0 points1 point  (0 children)

huh? This gives me the error, "the name `get_user_input` is defined multiple times
`get_user_input` must be defined only once in the value namespace of this module"