nrxus / faux

Struct mocking library for Rust
https://nrxus.github.io/faux/
MIT License
411 stars 14 forks source link

How to mock stuff in external crates? #39

Closed svenstaro closed 3 years ago

svenstaro commented 3 years ago

Hey, cool crate! I'd really like to use it to mock methods in an external crate's struct but I can't really find an example on that. Basically, something like

#[faux::create]
use SomeOtherCrate::SomeStruct;

Is this currently possible?

nrxus commented 3 years ago

Unfortunately it is not possible to mock external crates. faux needs to have access to the structure of the struct and its methods and it won't get that from just an import.

If you control the external crate though, you can export the mocks under a feature so other crates can use those mocks.

The general advice for testing is already to not mock what you don't own. My recommendation is that if it is really impossible to use the real version in tests (i.e., using some I/O), then do a thin wrapped around it. This thin wrapped can be mocked and allows you to have structs and methods that are more specific to your domain rather than the more general methods in the crate.

svenstaro commented 3 years ago

Alright, thanks. After quite a bit of research, I've come to the same conclusion. Though for complex foreign types, it's quite annoying to write a wrapper especially if the type is heavily generic. While not strictly in scope of this issue, do you have some advice on how to more conveniently generate a wrapping derived type for the purposes outlined above?

nrxus commented 3 years ago

It depends on your use case, if what you want from it is simple then make the wrapper simple by removing all the generics out of it, or at least the ones that you don't need today.

A benefit of writing this wrapper is that it let's you simplify the external API by making it focus on your need/domain rather than the general need that it was built for. And as a general rule of thumb, even if you think that maybe you will need it to be generic in the future, if it doesn't need to be generic today then don't add that complexity until you need it.

svenstaro commented 3 years ago

Thanks, we can consider this closed. However, I'd advise to change your readme as currently you mention the ability to mock external methods which doesn't seem to be possible.

nrxus commented 3 years ago

In the README I mentioned mocking methods in external modules as you can mock methods of structs from other modules, just not from other crates. I see how this can misleading though, do you have ideas on a better wording?

svenstaro commented 3 years ago

How about plainly Methods in external modules (though not external crates)?

nrxus commented 3 years ago

c55de6fb173fbbe3bbc75b5d910967353345018a