-
Hi, I'm new at using mocks in rust. I'm trying to test a trait with a constructor that has parameters like so: #[cfg(test)]
use mockall::{automock, predicate::*};
#[cfg_attr(test, automock)]
pub trait MyTrait {
fn new<S>(param1: S, param2: S) -> Option<Self>
where
S: Into<String> + 'static,
Self: std::marker::Sized;
}
#[cfg(test)]
mod tests {
use crate::{MyTrait, MockMyTrait};
#[test]
fn create_test() {
// how to setup expectation ???
let mock = MockMyTrait::new("param 1", "param 2");
assert!(mock.is_some());
}
} The test fails with: thread 'tests::create_test' panicked at 'MockMyTrait::new(?, ?): No matching expectation found' If I look at the generated code, I can see that there is a function for mocking the impl MockMyTrait {
///Create a [`Context`](__mock_MockMyTrait_MyTrait/__new/struct.Context.html) for mocking the `new` method
pub fn new_context() -> __mock_MockMyTrait_MyTrait::__new::Context {
__mock_MockMyTrait_MyTrait::__new::Context::default()
}
} But I'm not sure how to use it... I would like to set it up so that it returns Some(MockMyTrait). Later I'll add other functions to the trait that I can mock/test, but the standard use case is the create a new struct that implements the trait, verify that the #[cfg_attr(test, automock)]
pub trait MyTrait {
fn new<S>(param1: S, param2: S) -> Option<Self>
where
S: Into<String> + 'static,
Self: std::marker::Sized;
fn operation(&self) -> Result<State, Error>;
}
#[cfg(test)]
mod tests {
use crate::{MyTrait, MockMyTrait};
#[test]
fn create_test() {
let mock = MockMyTrait::new("some param 1", "some param 2");
assert!(mock.is_some());
let mut mock = mock.unwrap();
mock.expect_operation().returning(|| Ok(State::Connected));
assert_eq!(mock.operation(), Ok(State::Connected));
}
} Any help would be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Since your trait has a |
Beta Was this translation helpful? Give feedback.
Since your trait has a
new
method, Mockall doesn't generate the usual one. Instead,new
works like a normal method and you must make an expectation for it. If you want to create a new mock object with no expectations, you'll have to useMyTrait:::default()
.