"TRAITS"テンプレートパラメータを取るオブジェクトをテストする単位テスト
-
11-12-2019 - |
質問
私は、静的メソッドを公開するトラティテンプレートパラメータを使用するクラスを単体テストしたい(ポリシーベースの設計、戦略パターン)をテストします。Google TestとGoogle Mockフレームワークを使用しています。
例えば:
/// 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();
};
.
明らかにこれはそのままでは機能しません。Google Mockは静的メソッドを偽造することはできません、そして、私はその動作と期待を設定するためにテストでモッククラスのインスタンスを作成する必要があります。
それでは、Google Test / Google Mockを使用してテンプレートポリシーを受け入れるクラスをテストする正しい方法は何ですか?
解決
静的なメソッドを使用してクラスを作成でき、そのグローバルインスタンス(またはあなたの特性に静的)を作成し、それに特性クラスを遅延させますか?
だから、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;
...
}
.
私は上記をテンプレート化し、ほとんどパターンに変わったことを想像しています...多分。
所属していません StackOverflow