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

Use EXPECT_CALL on local object of function?

有没有办法在函数的局部对象上使用 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;
}