0

C++ でクラスの単体テストを行っていますが、パブリック メソッドの一部がプライベート メソッドを呼び出しています。パブリック インターフェイスをテストするのが慣例であることは知っていますが、クラスの機能は、これらのプライベート メソッドが他のクラスとそのメソッドを呼び出す方法に依存します。これは、プライベート関数に何が起こっても API に準拠するという意味で、パブリック インターフェイスに似ています。

ほとんどの場合、プライベート関数で呼び出されたクラスをモックして API をテストすることができましたが、いくつかのケースでは、標準ライブラリが参照されている場所に出くわし、それをモックできませんでした。標準ライブラリ クラスなどをモックするためのトリックはありますか? または、それらをスキップする必要がありますか?

-- また、ソースを変更したり、モック ライブラリを使用したりすることもできません。

4

4 に答える 4

3

If you really wish to mock the standard library then the easiest (possibly only) approach is to instrument your code correctly. That is, instead of using the headers and std namespace directly you'll have to use an intermediary name.

So invent a namespace, call it mstd. In your mocked mode this will be your mock namespace. In non-mock mode this will simply be an alias to std.

For header files you'll have to avoid including the standard headers directly, but use a mocking layer. So instead of including <map> you could include <mk-map>. This header file will then decide between the standard library and your version. Perhaps like this:

#ifdef MOCK_MODE
    #include "mock/map.hpp"
#else
    #include <map>
#endif

You could alternately give a different include path to your compiler, one that comes before the standard libraries. However, since you have to alias the namespace anyway you'll still have to modify all of your code -- thus it's just as easy to include these special headers.

This is about the only way I can see this working. Note that using LD_PRELOAD or any library technique will not work: the C++ standard library is made up of a lot of template classes and inline functions. You need to replace them right at compile time.

于 2011-07-07T05:38:55.620 に答える
2

クラスのプライベート メソッドのホワイトボックス テストを行おうとしている場合、コンパイラでアクセス制御をバイパスできるのではないでしょうか? -fno-access-controlGCCは少なくともunordered_{set,map}.

アクセス制御をスキップすると、他の呼び出しの合間にメンバー変数を直接いじることもできます。

于 2011-07-07T04:23:52.110 に答える
0

標準ライブラリのモックアップを作る必要は本当にあるのでしょうか? 確かに、標準ライブラリ関数にバグがある可能性はありますが、モックアップ自体にバグがある可能性は高いでしょう。

そのまま使ってくださいと言う事です。テストの失敗を標準ライブラリまで追跡すると、標準ライブラリのバグが見つかりました。そして、少なくとも当面は、そのようなバグを回避する方法を見つけなければならないでしょう。

于 2011-07-07T02:30:15.270 に答える