Closed DE-mohammad closed 2 years ago
Your problem is that the mock object never drops. Normally, if a mock object is expected to be called but never gets called, that will trigger a panic when the mock object drops. But in both of these cases, the mock object never drops. So while by the end of your test function the expectation hasn't been satisfied yet, it conceivably might be satisfied in the future. I don't think there's any way for Mockall to provide the behavior you want, because Mockall doesn't know when your test function ends.
But there's an easy solution! Just call the mock object's checkpoint
method at the end of your test, like this:
#[test]
fn test_static_mock() {
MOCK_MY_STRUCT.lock().unwrap()
.expect_foo()
.times(1)
.return_const(());
MOCK_MY_STRUCT.lock().unwrap().checkpoint();
}
Thank you for the quick response. That makes sense and clarifies things quite a bit, and it solved my issue perfectly.
I'm having an issue with mocking external traits, and it seems that if, when an external trait is mocked with a struct, and the new generated mock struct is accessed with a mutable reference in order to set expectations, then a test passes incorrectly in certain specific circumstances. The reason I needed to do this is that my application requires a function call to take an instance of the (mocked) struct, and that struct is bound by a static lifetime. In the examples below, I use [
lazy_static
]() to create a global mutable singleton on a Mutex lock, or I useBox::leak()
to create a variable inside a function with a static lifetime.Here is an example of this issue occurring with
lazy_static
:Here is another example using
std::Box::leak
instead:In both examples, the test
test_static_mock()
passes incorrectly as per this output.EDIT: typo,
test_static_mock()
PASSES incorrectly