gtest如何測試private成員

最近在使用gtest,但有個問題,對私有成員無法訪問。


我瞭解到的比較流行的兩種做法是:
1. 將test class作爲被測class的友元(friend);
2. 使用hack compiler的方法:#define private protected

兩種方法個有優缺點,下面簡單分析下:

1. 將test class作爲被測class的友元(friend)

這是一種compiler比較接受的方法,但是缺點是你在開發class時就得頂好test class的名字,把他加爲friend,這樣,test class和被測class之間耦合太緊密。
而且被測class編譯後的目標代碼中始終留有test class的痕跡。

2. 使用#define private protected

這種方法是我比較贊同的方法,被測class無需知道anything,與test class之間的耦合非常低。
具體做法是:

// test.cpp:
#define private public  // hack complier
#define protected public

#include "my_class.h" // all private/protected members now become public!

#undef private
#undef protected

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章