How to unit test one struct method while mocking other methods? #466
-
Say I have a struct struct Foo { ... };
struct Bar { ... };
impl Foo {
fn method_1(&self) -> Bar {
// Complex code
}
fn method_2(&self) {
// Complex code
let result = self.method_1();
// Complex code
}
} How can I write a unit test for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The short answer is that you can't. Mockall replaces the entire object with a mock version. You might be able to get away with the following, if #[automock]
impl Foo {
fn method_1(&self) -> Bar {
...
}
}
impl Foo {
fn method_2(&self) {
....
}
} However, that strategy will break down if mod foo {
struct Foo {...}
#[automock]
impl Foo {...}
}
mod bar {
#[double]
use crate::foo::Foo;
struct Bar{foo: Foo, ...}
#[automock]
impl Bar {...}
}
mod baz {
#[double]
use crate::bar::Baz;
struct Baz {bar: Bar, ....}
} |
Beta Was this translation helpful? Give feedback.
The short answer is that you can't. Mockall replaces the entire object with a mock version. You might be able to get away with the following, if
method_2
doesn't access any of the struct's data:However, that strategy will break down if
method_2
tries to access any struct data. Instead, a better strategy is to separate the object into two. Not just in your test code, but in your product code as well. Arrange it in layers, such that you can mock the lower layer when testing the higher one. That's what I do. Like this: