2016-03-15 28 views
3

我需要Gtest一個單例類的私有方法。我嘗試使用單身人士的朋友類。但沒有幫助。 它說私人不能被稱爲。我添加了類,Gtest嘗試過,輸出錯誤。隨時問任何更多的澄清,提前感謝! 如果請忽略錯別字任何..如何在C++中使用Normal或Singleton類中的私有方法/枚舉類

下面的Singleton類中Gtested:

class Listener: public CommonListen { 
public: 
    friend class test_listener; 
    Listener(task_id taskid, const string thread_name) : 
    CommonListen(taskid, thread_name) { } 
    static Listener* GetInstance() { 
    if (Listener_ptr_ == nullptr) { 
     Listener_ptr_ = new 
      Listener(LISTENER_ID, ListenerName); 
    } 
    return Listener_ptr_; 
    } 

private: 
    // Override the base's method 
    void SetupPub(); 
    static Listener* Listener_ptr_; 
}; 

我累GTEST使用Friend類象下面這樣:

class test_listener : public ::testing::Test { 
public: 
    void call_private(void); 
}; 

TEST_F(test_listener, create_listener) { 
    call_private(); 
} 
void test_listener::call_private() { 
    (Listener::GetInstance())->SetupPub(); 
} 

拋出錯誤象下面這樣:

error: 'virtual void Listener::SetupPub()' is private 
    void SetupPub(); 
     ^
test_listener.cc:48:63: error: within this context 
    (Listener::GetInstance())->SetupPub(); 
                  ^
make[2]: *** [test_listener.o] Error 1 

請分享您的看法

@@@@不工作案例:@@@@

class xxx : public yyy { 
    friend class test_xxx; 

    enum class State : std::int8_t { SSS = 1, 
     DDD, FFF}; 
    enum class AlignmentFlags : std::int8_t { ZZZ= 1, 
     CCC= 2, VVV= 4, BBB= 8, 
     NNN= 3, MMM= 12}; 

public: 
    // ********** 
} 

在呼籲 「的#define公私」 後下方erroroccurs使用上述私人枚舉類:

../src/qqq/xxx.h:189:14: error: 'enum class 
xxx::AlignmentFlags' is private 
    enum class AlignmentFlags : std::int8_t { ZZZ = 1, 

訪問像:

xxx->SetAlignmentFlags(12); 
+0

爲什麼它是私密的? –

+0

@AntonioPérez:我沒有理由把它當作私人。由於要測試的源代碼不是由我寫的:-)。但Usecase是如何Gtest一個Singleton類私有方法... – Ragav

+0

@Mark B ..我的問題是不同的方式,它與單身人士和更多的精確的代碼寫成片張貼與清晰度.Also其他職位並沒有完全提出處理這種測試的正確方法。 – Ragav

回答

0

您可以添加以下您GTEST CPP文件的第一行,你有任何事情之前:

#define private public 

這會讓你的測試訪問您的類的所有私有成員,因爲它們會被編譯爲公衆。

+0

這是常見的做法嗎? – Pierre

+0

@Marc O'Morain:謝謝......我會嘗試在CPP Gtest文件中的#include之前添加這個#define並讓你知道。 – Ragav

+0

@PierreI我希望這不是一種常見的做法:)我曾嘗試使用遊戲開發中間件時必須這樣做。有時您需要訪問的字段被標記爲「私人」。 –