在google mock中返回对unique_ptr的引用

时间:2018-01-02 10:03:31

标签: c++ unit-testing googletest googlemock

我在google mock中返回对唯一指针的引用时遇到问题。 我有一个对象Foo,有一个方法操作(),我试图在google test / google模拟框架中测试:

class Foo {
public:
  Foo(BarInterface &bar) : bar{bar} {};
  virtual ~Foo() = default;
  void operate() { bar.getBaz()->startMeUp(); }
private:
  BarInterface &bar;
};

测试类看起来像这样:

using ::testing::StrictMock;
using ::testing::ReturnRef;

class FooTest : public ::testing::Test {
protected:
  StrictMock<BarMock> barMock;
  std::unique_ptr<StrictMock<BazMock>> bazMock {new StrictMock<BazMock>()}; // This might be incorrect

  Foo *foo;
  virtual void SetUp() {
    foo = new Foo(barMock);
  }

  virtual void TearDown() {
    delete foo;
  }
};

TEST_F(FooTest, BasicTest) {
  EXPECT_CALL(barMock, getBaz()).WillOnce(ReturnRef(bazMock)); // Gives compilation error
  EXPECT_CALL(*bazMock, startMeUp()); // Gives compilation error
  foo->operate();
}

正如你所看到的,我有两个被嘲笑的对象,Bar和Baz。 Baz mock有一个方法,startMeUp():

class BazInterface {
public:
  virtual ~BazInterface() = default;
  virtual void startMeUp() = 0;
};

class BazMock : public BazInterface {
public:
  MOCK_METHOD0(startMeUp, void());
};

Bar方法getBaz()根据以下内容返回对唯一指针的引用:

class BarInterface {
public:
  virtual ~BarInterface() = default;
  virtual std::unique_ptr<BazInterface>& getBaz() = 0;
};

class BarMock : public BarInterface {
public:
  MOCK_METHOD0(getBaz, std::unique_ptr<BazInterface>&());
};

问题是(至少)我无法正确获得两个EXPECT_CALL()。我试图以几种方式返回bazMock,但我总是遇到编译错误。 我也尝试通过返回对shared_ptr甚至普通指针的引用来简化问题,但我也无法进行编译。 有人可以帮助我做对吗?

这是编译输出:

gmock-actions.h: In instantiation of 'testing::internal::ReturnRefAction<T>::Impl<F>::Result testing::internal::ReturnRefAction<T>::Impl<F>::Perform(const ArgumentTuple&) [with F = std::unique_ptr<BazInterface>&(); T = std::unique_ptr<testing::StrictMock<BazMock> >; testing::internal::ReturnRefAction<T>::Impl<F>::Result = std::unique_ptr<BazInterface>&; testing::internal::ReturnRefAction<T>::Impl<F>::ArgumentTuple = std::tuple<>]':
foo_test.cc:30:1:   required from here
gmock-actions.h:683:14: error: invalid initialization of reference of type 'testing::internal::ReturnRefAction<std::unique_ptr<testing::StrictMock<BazMock> > >::Impl<std::unique_ptr<BazInterface>&()>::Result {aka std::unique_ptr<BazInterface>&}' from expression of type 'std::unique_ptr<testing::StrictMock<BazMock> >'
   return ref_;

1 个答案:

答案 0 :(得分:0)

最好的解决方法是更改​​BarInterface的界面,以返回对BazInterface的引用,而不是引用unique_ptr。无需将指针暴露给BarInterface用户 如果您坚持要返回对unique_ptr的引用,请执行以下操作:

class BarMock : public BarInterface
{
public:
    BarMock(std::unique_ptr<BazInterface> baz) {this->baz = std::move(baz);}

    override std::unique_ptr<BazInterface>& getBaz(){
        getBazWrapped();
        return baz;
    }
    MOCK_METHOD0(getBazWrapped, void());
private:
    std::unique_ptr<BazInterface> baz;
};

并在FooTest

BazMock * bazMock { new <StrictMock<BazMock> };
BarMock barMock { std::unique_ptr<BazInterface>(bazMock)};