此問題來自一個真實世界的項目,該項目使用「經常在基類中提供受保護的接口」模式。重構受保護的基類依賴項測試
這裏有一個小例子:
class UntouchableBase
{
protected: //cannot be called from outer class
int GetValue() { return 42;}//not virtual
//this class has many many more "protected interface" methods
};
class HeavyWeightClassIWantToTest: public UntouchableBase
{
public:
// VeryHeavyClassIWantToTest(...) {} //ignore the creation issue for a heavy weight object here
void MethodThatNeedsTest()
{
//calc some values
int result = GetValue();
//do some other stuff
}
};
我在尋找一種快速,無創大多重構,以取代的GetValue依賴。 提取方法和添加新的類允許HeavyWeightClassIWantToTest
@UPDATE:測試,來說明這個問題
TEST(EnsureThat_MyMethodThatNeedsTestDoesSthSpecial)
{
HeavyWeightClassIWantToTest sut = MakeSut();
sut.MethodThatNeedsTest(); //should call a mocked/replaced GetValue()
}
提示:目前,我們正在使用的接頭縫更換UntouchableBase
執行用於測試目的。
請提供編碼示例。
老虎屁股摸不得是'UntouchableBase'?你可以修改頭文件,甚至沒有?那麼'class TestableBase:public UntouchableBase',然後從'TestableBase'派生'HeavyWeightClass'? –
UntouchableBase的變化成本非常高。您不能直接重載,因爲GetValue()方法不是虛擬的。 – mrAtari
我認爲你的意思是「重寫」而不是「重載」,但是假如沒有人在做'pUntouchableBase-> GetValue()',你可以用中間類中的版本來隱藏函數。 –