In the example below, I want to unit test class A
in order to verify that when A::request
is called, B::response()
is called as well:
class A
{
public:
void request()
{
m_b.response();
}
private:
B m_b;
};
class B
{
public:
void response();
};
In order to do that, class B
has to be mocked:
class MockB : public B
{
public:
MOCK_METHOD0( response, void());
};
So that the test will contain:
class TestA : public A
{
...
};
...
EXPECT_CALL( m_b, response( ) ).Times( 1 );
request( );
...
The question is: how to "inject" MockB
as a replacement of B m_b
?
First tecnique: Create a ShadowB
class that redirects the method call to class MockB
. This requires the original code to be in an external binary, but does not require any change in the actual code.
Second tecnique:
- Making
B::response
virtual
- Changing
B m_b
to astd::unique_ptr<B> m_b
- Replace
m_b
value with an instance ofclass MockB
during the test setup
Second approach means more code change and I'm not sure about its pro.
Aucun commentaire:
Enregistrer un commentaire