c++ - Google Test Framework: is better to use shadowing or virtual methods? -


in example below, want unit test class a in order verify when a::request called, b::response() called well:

class { public:     void request()     {         m_b.response();     }  private:     b m_b; };  class b {  public:     void response(); }; 

in order that, class b has mocked:

class mockb : public b { public:     mock_method0( response, void()); }; 

so test contain:

class testa : public {     ... };  ... expect_call( m_b, response( ) ).times( 1 ); request( ); ... 

the question is: how "inject" mockb replacement of b m_b?

first tecnique: create shadowb class redirects method call class mockb. requires original code in external binary, not require change in actual code.

second tecnique:

  • making b::response virtual
  • changing b m_b std::unique_ptr<b> m_b
  • replace m_b value instance of class mockb during test setup

second approach means more code change , i'm not sure pro.

the correct way of solving problem second technique. more generally, hard 'retro-fit' unit testing code onto components not designed in mind - need modify code being tested.

using virtual functions substitute mock callback objects in place of real ones, both inheriting common interface common approach. alternative have classes being tested template classes, , replace template parameters mock objects.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -