Extracting a trait from a struct, when that trait is only going to be used once

I have a method defined in the impl block for a struct. I want to mock it out as part of a unit test, and have been investigating mockers. In the user guide, it says that while it is possible with some extra effort to mock out struct impls (see Mocking structures),

Ideally, of course, you should extract a trait and make AirConditioner implement this trait.

Is that a good pattern, in general? If I have my Tab struct (representing a browser tab), and some of its methods are related to finding DOM elements on the page via CSS selectors, should I put them in their own trait and write an implementation for Tab, even though Tab (for the foreseeable future) will be the only struct to implement it?

If you’re neutral towards that idea, how would you feel about my extracting the trait just to make it easier to work with mockers?

Finally, do you think it’s okay to split the new trait (and the one implementation) out into its own file?

Cheers!

While experimenting with this, it seems like it would require any consumers of those methods to explicity use that trait before they used any of the methods defined on it, which is pretty burdensome. Is there any way around that?

What about something like this:

    pub
    struct Foo;
    
    trait Method {
        fn method (&self);
    }

    impl Method for Foo {
        fn method (&self)
        {
            println!("Called Foo::method()");
        }
    }
    
    impl Foo {
        #[inline]
        pub
        fn method (&self)
        {
            <Self as Method>::method(self)
        }
    }

Foo has an inherent method .method() that just delegates to the trait, so the trait can even be private! (or #[doc(hidden)] pub for integration tests). And now mocking method can be done with, for instance, different implementations of the trait based on #[cfg(test)]

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.