gpt4 book ai didi

c++ - 在函数的局部对象上使用 EXPECT_CALL?

转载 作者:行者123 更新时间:2023-11-28 04:54:39 26 4
gpt4 key购买 nike

有没有办法在函数的局部对象上使用 EXPECT_CALL?

例如:

template<class T>
std::string doSomethingWithTheCar()
{
T car;
return "the color of the car is: " + car.color();
}

class Car
{
public:
std::string color()
{
return "green";
}
};

class MockCar
{
public:
MOCK_METHOD0(color, std::string());
};

TEST(MockLocalObject, doSomethingWithCarTest) {
EXPECT_CALL(car, color())
.WillOnce(Return("red"));

std::string color = doSomethingWithTheCar<MockCar>();
EXPECT_EQ(color, "red");
}

由于模板,我可以控制是使用真实的 Car 对象还是 MockCar。但是有没有办法在这上面使用 EXPECT_CALL

最佳答案

我会这样做:

class AbstractCar {
public:
virtual ~AbstractCar() = default;
virtual std::string color() = 0;
};

class Car: public AbstractCar {
public:
~Car() override = default;
std::string color() override {
return "green";
}
};

class MockCar: public AbstractCar {
public:
MOCK_METHOD0(color, std::string());
};

std::string doSomethingWithTheCar(AbstractCar* car) // or even better - use std::shared_ptr
{
return "the color of the car is: " + car->color();
}

TEST(MockLocalObject, doSomethingWithCarTest) {
auto car = new MockCar;
EXPECT_CALL(*car, color()).WillOnce(Return("red"));

std::string color = doSomethingWithTheCar(car);
// this test will fail, because actual string is:
// "the color of the car is: red"
EXPECT_EQ(color, "red");
delete car;
}

关于c++ - 在函数的局部对象上使用 EXPECT_CALL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com