[英]Mock base class function called in derived class; to unit test derived class method. Base class instantiated in derived class constructor
我是單元測試的新手,需要一些幫助。 我想測試我的 Derived class function 依賴於基礎 class 方法。
class Base { Base(int a_, int b_){ a = a_; b = b_; } int a; int b; int GetBaseValue(){ return a + b; } } class Derived: public Base { Derived(int c,int a,int b): c_(c), Base(a,b){} int GetDerivedValue(){ return c + GetBaseValue(); } }
為了使您的示例工作和測試僅與Base
Derived
分離(順便說一句, Base
應該有自己的一組單元測試),您需要使Base::GetBaseValue
成為虛擬方法並模擬它。
class Base { public: Base(int a_, int b_){ a = a_; b = b_; } virtual int GetBaseValue(){ return a + b; } private: int a; int b; }; class Derived: public Base { public: Derived(int c,int a,int b): c_(c), Base(a,b){} int GetDerivedValue(){ return c_ + GetBaseValue(); } private: int c_; }; class PartialDerivedMock: public Derived { public: using Derived::Derived; MOCK_METHOD(int, GetBaseValue, (), (override)); }; TEST(PartialDerivedMockTest, UseMockedGetBaseValue) { PartialDerivedMock out{1, 2, 3}; EXPECT_CALL(out, GetBaseValue()).WillOnce(testing::Return(42)); ASSERT_EQ(out.GetDerivedValue(), 43); }
但是由於您在問題中使用了關鍵字“依賴”:請讓我給您一些建議。 使用 inheritance 是兩個類之間非常非常強大的連接。 在 OOP 中,將一些邏輯上一致的代碼部分委托給單獨的 class 是個好主意,但使用 inheritance 來(重新)使用此代碼 - 不多。 請考慮這一點:
//now: with the dependency class Dependency { public: ~Dependency() = default; virtual int GetValue() = 0; }; class Dependant { public: Dependant(int c, Dependency& dep): c_(c), dependency{dep}{} int GetSomeValue(){ return c_ + dependency.GetValue(); } private: int c_; Dependency& dependency; }; class DependencyMock: public Dependency { public: MOCK_METHOD(int, GetValue, (), (override)); }; TEST(DependencyTest, UseMockedGetBaseValue) { DependencyMock mock{}; Dependant out{1, mock}; EXPECT_CALL(mock, GetValue()).WillOnce(testing::Return(42)); ASSERT_EQ(out.GetSomeValue(), 43); }
遵循 SOLID 原則,您可以獲得兩個類做不同事情的好處(S),接口 class 在實現更改時不會被修改(在某種程度上是 O 和 L)和真正的反向依賴關系(D)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.