Skip to content

How to unit test one struct method while mocking other methods? #466

Answered by asomers
rharish101 asked this question in Questions
Discussion options

You must be logged in to vote

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:

#[automock]
impl Foo {
    fn method_1(&self) -> Bar {
        ...
    }
}
impl Foo {
    fn method_2(&self) {
        ....
    }
}

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:

mod foo {
    struct Foo {...}
    #[automock

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@rharish101
Comment options

Answer selected by rharish101
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants