asomers / mockall

A powerful mock object library for Rust
Apache License 2.0
1.45k stars 61 forks source link

Mocking a Generic Trait with mock! Macro: 'Type Parameter Not Constrained' Error #588

Closed rotmanben closed 2 months ago

rotmanben commented 2 months ago

I'm trying to mock a generic trait using mock! but but I'm getting this compiler error: "the type parameter T is not constrained by the impl trait, self type, or predicates"

Here's the relevant code:

pub trait SaveTx<T>
where
    T: TransactionType + Send + Sync + 'static,
{
    async fn save_tx(&self, txs: Vec<T>) -> Result<()>;
}

mock!{
    pub DbClient {}
    impl<T> SaveTx<T> for DbClient
    where
    T: TransactionType + Send + Sync + 'static,
    {
       async fn save_tx(&self, txs: Vec<T>) -> Result<()>;
    }
}

Is there a workaround or a correct way to do that? I'm relatively new to this library, so any guidance would be appreciated.

Thanks a lot :)

asomers commented 2 months ago

You probably want your mock type to be generic, right? If so, do pub DbClient<T>. If not, then you probably want to impl a specific instantiation of the trait, like SaveTx<u32>.

rotmanben commented 2 months ago

You probably want your mock type to be generic, right? If so, do pub DbClient<T>. If not, then you probably want to impl a specific instantiation of the trait, like SaveTx<u32>.

Thank you for the suggestion! Implementing a specific instantiation of the trait solved my issue

asomers commented 2 months ago

Glad to help.