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 ofclass 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
Post a Comment