小编Spi*_*rit的帖子

单元测试硬件的应用程序接口 - 模拟与否

我非常好奇人们对于与硬件接口的软件端应用程序应该以何种方式进行单元测试的意见.

例如,软件应用程序"连接"的主类将构建USB设备的句柄.

我想测试"Connection"类基本函数,比如"OpenConnection",它会尝试连接到USB硬件设备.

到目前为止我已经构建了一个MOCK硬件设备,并且在我的连接类中包含了一个编译器标志,所以如果它内置单元测试模式,它将使用一个模拟对象,另外它会使用实际的硬件接口.

见下面的例子

class TConnection
{
public:
    static TConnection* GetConnection();
    static void Shutdown();

    bool DidInitialise();

    bool Write(uint8_t* _pu8_buffer);
    bool Read(uint8_t* _pu8_buffer);

protected:
    TConnection();
    virtual ~TConnection();
    bool init();

private:
    static TConnection* mp_padConnection;
    static bool mb_DidInitialise;

#ifdef _UNIT_TEST_BUILD
    static mock_device* mp_handle;
#else
    static device* mp_handle;
#endif
};
Run Code Online (Sandbox Code Playgroud)

然后在源文件中包含类似的内容

#include "connection.h"

#ifdef _UNIT_TEST_BUILD
    mock_device* TConnection::mp_handle = nullptr;
#else
    device* TConnection::mp_handle = nullptr;
#endif // _UNIT_TEST_BUILD

TConnection::TConnection()
{
    ...
    init();
    ...
}

bool TConnection::init()
{
    mp_handle = hid_open( _VENDOR_ID, _PRODUCT_ID, nullptr ); …
Run Code Online (Sandbox Code Playgroud)

c++ unit-testing googletest c++11

2
推荐指数
1
解决办法
1116
查看次数

标签 统计

c++ ×1

c++11 ×1

googletest ×1

unit-testing ×1