设定期望值后,我可以复制Google模拟对象吗? [英] Can I copy a google mock object after setting expectations?

查看:71
本文介绍了设定期望值后,我可以复制Google模拟对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的测试治具类中添加一个实用程序函数,该函数将返回具有特定期望/动作集的模拟.

I want to add a utility function in my test fixture class that will return a mock with particular expectations/actions set.

例如:

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.
}

不幸的是我得到了

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?

很明显,我可以使getSpecialListener返回一个MockListener& ;,但是它不必成为MyTest的成员,并且由于只有某些测试使用了该特定模拟(并且我仅应在测试时填充模拟行为).正在使用它),这样会不太干净.

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.

推荐答案

模拟对象是不可复制的,但是您可以编写一个工厂方法来返回指向新创建的模拟对象的指针.要简化对象所有权,可以使用std::unique_ptr.

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.
}

这篇关于设定期望值后,我可以复制Google模拟对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆