问题
I want to add a utility function in my test fixture class that will return a mock with particular expectations/actions set.
E.g.:
class MockListener: public Listener
{
// Google mock method.
};
class MyTest: public testing::Test
{
public:
MockListener getSpecialListener()
{
MockListener special;
EXPECT_CALL(special, /** Some special behaviour e.g. WillRepeatedly(Invoke( */ );
return special;
}
};
TEST_F(MyTest, MyTestUsingSpecialListener)
{
MockListener special = getSpecialListener();
// Do something with special.
}
Unfortunately I get:
error: use of deleted function ‘MockListener ::MockListener (MockListener &&)’
So I assume mocks can't be copied? Why, and if so is there another elegant way to get a function to manufacture a ready-made mock with expectations/actions already set?
Obviously I can make the getSpecialListener return a MockListener&, but then it would unnecessarily need to be a member of MyTest, and since only some of the tests use that particular mock (and I should only populate the mock behaviour if the test is using it) it would be less clean.
回答1:
Mock objects are non-copyable, but you can write a factory method that returns a pointer to a newly created mock object. To simplify the object ownership, you can use std::unique_ptr
.
std::unique_ptr<MockListener> getSpecialListener() {
MockListener* special = new MockListener();
EXPECT_CALL(*special, SomeMethod()).WillRepeatedly(DoStuff());
return std::unique_ptr<MockListener>(special);
}
TEST_F(MyTest, MyTestUsingSpecialListener) {
std::unique_ptr<MockListener> special = getSpecialListener();
// Do something with *special.
}
回答2:
Well it seems not possible to copy mock class instances properly, especially not deep copying any expectations bound to them.
What you though can do is, to provide helper functions in your test class, that set up specific expectations on mock instances, like:
class MyTest: public testing::Test {
public:
MockListener& setSpecialListenerExpectations(MockListener& special)
// ^ ^
{
EXPECT_CALL(special, /** Some special behaviour e.g. WillRepeatedly(Invoke( */ );
return special;
}
};
and make them special in your test case:
TEST_F(MyTest, MyTestUsingSpecialListener) {
MockListener special;
setSpecialListenerExpectations(special);
// Do something with special.
}
来源:https://stackoverflow.com/questions/33043640/can-i-copy-a-google-mock-object-after-setting-expectations