Hi, I currently struggle with a simple pattern to properly use mock in a unit test. In most language you would normally make a constructor where you can inject your mock and have an overload where you do not take any parameter so the normal object creation you occur.
With this approach I can freely change the socket implementation in my test, but I need to 'leak' the Internal trait from outside my module. Any tips or advice on this ?
I suggest you only use mocks in your unit tests, not your integration tests. That way you won't have to leak the details out of your crate. Furthermore, I suggest you use Mockall to help you write your tests. It can mock structs, so you won't need to define the Internal trait. You can do it a little like this:
Sorry for the late reply. In your example, are you missing a dyn keyword like so
pub struct Client {
socket: dyn UnixDatagram
}
Other wise the size won't be know at compile time. You can always use a box right ? For my case the trait have more method with a generic type. So I can't have a trait object.
Yes this work if the struct is in a module I owned. But in this case UnixDatagram is from std::os::unix::net module. So I need to use the mock! macro to create the mock. I think this is what the first answer was proposing. So yeah no dyn require and no generic. Sorry I was not aware of the double macro.