trompeloeil
trompeloeil copied to clipboard
Allow setting expectations in moved-from mocks
I have a class I want to test that is taking ownership of a mock I pass to it. This means I need to set all the expectations before passing the mock to my object. I was wondering whether it would be possible to (conditionally) give a method to the mock objects that would return a "handle" that would allow me to keep adding expectation to a mock after I have moved it.
So I guess the mock class would end up being something like
class mock {
public:
class mock_impl {
// All the magic
};
class mock_handle {
public:
void mock_method() {
auto impl = impl_.lock();
assert(impl);
impl->mock_method();
}
private:
std::weak_ptr<mock_impl> impl_;
};
mock_handle get_mock_handle() { return mock_handle{impl}; }
void mock_method() { impl_->mock_method(); }
private:
std::shared_ptr<mock_impl> impl_;
};
This would allow me to do something like this:
TEST_CASE {
mock_t mock;
auto mock_handle = mock.get_mock_handle();
test_t test{std::move(mock)};
TEST_SUBCASE {
auto expectations1 = set_named_mock_expectations(mock_handle);
make_test_move(test);
expectations1.reset();
TEST_SUBCASE {
auto expectations2 = set_named_mock_expectations(mock_handle);
make_test_move(test);
expectations2.reset();
}
}
}
I feel very uncomfortable about this. The norm for all moved from objects is that they are in an indeterminate (the phrase used in the standard is "valid but unspecified") state. The only well specified example in the standard library, that I can think of, is unique_ptr<>
, which is defined to be null when moved from. I fear that trying to figure out a generic solution for trompeloeil
may cause a lot of trouble for debatable gain.
However, there's nothing preventing you from defining whatever semantics you need in your own classes. Yes, that means work for you rather than for the library, but in this case I think that is preferable.
Coming from Rust world for a moment I'd say the idea is valid as taking ownership of the dependency makes a lot of sense in certain exclusive resources (my eyes are turned on embedded systems now).
I'd vote for such addition.