在本地函数对象上使用EXPECT_CALL?

时间:2017-11-23 14:48:56

标签: c++ testing googletest googlemock

有没有办法在函数的本地对象上使用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

1 个答案:

答案 0 :(得分:2)

我会这样做:

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