Skip to content

Instantly share code, notes, and snippets.

@biot023
Created May 2, 2012 16:30
Show Gist options
  • Save biot023/2577969 to your computer and use it in GitHub Desktop.
Save biot023/2577969 to your computer and use it in GitHub Desktop.
#include "gmock/gmock.h"
#include <iostream>
#include <string>
#include <memory>
namespace poc {
using namespace std;
struct IPoc1
{
virtual ~IPoc1() {}
virtual const string get_str() const = 0;
};
struct Poc1 : public IPoc1
{
Poc1() : _msg( "Default Message" ) {}
Poc1( const string &msg ) : _msg( msg ) {}
virtual const string get_str() const { return _msg; }
private:
string _msg;
};
struct IPoc2
{
virtual ~IPoc2() {}
virtual const string get_str() const = 0;
};
struct Poc2 : public IPoc2
{
virtual const string get_str() const { return _get_poc1()->get_str(); }
private:
virtual shared_ptr<const IPoc1> _get_poc1() const {
return make_shared<const Poc1>();
}
};
}
namespace {
using namespace std;
using namespace poc;
using ::testing::Test;
using ::testing::Return;
using ::testing::Invoke;
using ::testing::Eq;
struct MockPoc1 : public IPoc1
{
MOCK_CONST_METHOD0( get_str, const string() );
};
struct PartMockPoc2 : public Poc2
{
PartMockPoc2()
{
ON_CALL( *this, get_str() )
.WillByDefault( Invoke( this, &PartMockPoc2::_pclass_get_str ) );
}
MOCK_CONST_METHOD0( get_str, const string() );
MOCK_CONST_METHOD0( _get_poc1, shared_ptr<const IPoc1>() );
private:
const string _pclass_get_str() const { return Poc2::get_str(); }
};
struct PocTest : public Test
{
protected:
string _msg;
shared_ptr<const MockPoc1> _poc1;
PartMockPoc2 _poc2;
PocTest() :
_msg( "mock poc1 string" ),
_poc1( make_shared<const MockPoc1>() )
{
EXPECT_CALL( *_poc1, get_str() )
.WillRepeatedly( Return( _msg ) );
EXPECT_CALL( _poc2, _get_poc1() )
.WillRepeatedly( Return( shared_ptr<const IPoc1>( _poc1 ) ) );
EXPECT_CALL( _poc2, get_str() );
}
const string _subject() const { return _poc2.get_str(); }
};
// Should instantiate a poc1
TEST_F( PocTest,
ShouldInstantiateAPoc1 ) {
EXPECT_CALL( _poc2, _get_poc1() )
.WillOnce( Return( shared_ptr<const IPoc1>( _poc1 ) ) );
_subject();
}
// Should call get_str on the poc1
TEST_F( PocTest,
ShouldCallGetStrOnThePoc1 ) {
EXPECT_CALL( *_poc1, get_str() )
.WillOnce( Return( _msg ) );
_subject();
}
// Should return the value of the poc1's call to get_str
TEST_F( PocTest,
ShouldReturnTheValueOfThePoc1sCallToGetStr ) {
EXPECT_THAT( _subject(), Eq( _msg ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment