testando a unidade de um objeto que usa um parâmetro de modelo “traits”
-
11-12-2019 - |
Pergunta
Eu tenho um projeto do Visual Studio 2008 C++ 03 onde gostaria de testar a unidade de uma classe que usa um parâmetro de modelo de características que expõe métodos estáticos (design baseado em políticas, padrão de estratégia).Estou usando as estruturas Google Test e Google Mock.
Por exemplo:
/// the class under test
template< typename FooTraits >
class Foo
{
public:
void DoSomething()
{
FooTraits::handle_type h = FooTraits::Open( "Foo" );
/* ... */
FooTraits::Close( h );
};
};
/// a typical traits structure
struct SomeTraits
{
typedef HANDLE handle_type;
static handle_type Open( const char* name ) { /* ... */ };
static void Close( handle_type h ) { /* ... */ };
};
/// mocked traits that I would like to use for testing
struct MockTraits
{
typedef int handle_type;
static MOCK_METHOD1( Open, handle_type( const char* ) );
static MOCK_METHOD1( Close, void( handle_type ) );
};
/// the test function
TEST( FooTest, VerifyDoSomethingWorks )
{
Foo< MockTraits > foo_under_test;
// expect MockTraits::Open is called once
// expect MockTraits::Close is called once with the parameter returned from Open
foo_under_test.DoSomething();
};
Obviamente, isso não funcionará como está.O Google Mock não pode simular métodos estáticos e eu precisaria criar uma instância da classe Mocked no teste para definir seu comportamento e expectativas.
Então, qual é a maneira correta de testar a unidade de uma classe que aceita uma política de modelo usando o Google Test/Google Mock?
Solução
Você pode criar uma classe com métodos não estáticos, criar uma instância global dela (ou estática em suas características) e fazer com que sua classe de características seja adiada?
Então, para esclarecer a ideia que foi inspirada no comentário de Rob:
struct FunnyDoodad
{
FunnyDoodad();
~FunnyDoodad();
MOCK_METHOD1( Open, HANDLE( const char* ) );
MOCK_METHOD1( Close, void( handle_type ) );
};
struct FunnyGlobal {
FunnyGlobal() : pimpl() {}
~FunnyGlobal() { delete pimpl; }
// You'd want some protection here rather than just dereferencing.
// it's the whole point. I'd suggest using whatever unit test assertion
// mechanism your framework uses and make it a fatal check.
handle_type Open(char const* name) { return pimpl->Open(name); }
void Close(handle_type h) { pimpl->Close(h); }
private:
FunnyDoodad * pimpl;
friend struct FunnyDoodad;
void register(FunnyDoodad* p) { pimpl = p; }
void deregister() { pimpl = 0; }
};
FunnyGlobal funnyGlobal;
FunnyDoodad::FunnyDoodad() { funnyGlobal.register(this); }
FunnyDoodad::~FunnyDoodad() { funnyGlobal.deregister(); }
struct TestTraits
{
typedef HANDLE handle_type;
static handle_type Open( const char* name ) { return funnyGlobal.Open(name); };
static void Close( handle_type h ) { funnyGlobal.Close(h); };
};
TEST_CASE(blah)
{
FunnyDoodad testDoodad;
...
}
Imagino que o que foi dito acima poderia ser modelado e quase transformado em um padrão... talvez.