cha*_*lup 5 c++ unit-testing pimpl-idiom
我正在开发一个为某些服务定义客户端接口的库.在引擎盖下,我必须验证用户提供的数据,然后使用来自另一个库的Connection类将其传递给"引擎"进程(注意:我们的库的用户不知道Connection类).我的一位同事建议使用PIMPL:
class Client {
public:
Client();
void sendStuff(const Stuff &stuff) {_pimpl->sendStuff(stuff);}
Stuff getStuff(const StuffId &id) {return _pimpl->getStuff(id);}
private:
ClientImpl *_pimpl;
}
class ClientImpl { // not exported
public:
void sendStuff(const Stuff &stuff);
Stuff getStuff(const StuffId &id);
private:
Connection _connection;
}
Run Code Online (Sandbox Code Playgroud)
但是,我发现很难测试 - 即使我将测试链接到一些模拟的Connection实现,我也无法轻松访问它来设置和验证期望.我错过了什么,或者更清洁,更可测试的解决方案是使用interface + factory:
class ClientInterface {
public:
void sendStuff(const Stuff &stuff) = 0;
Stuff getStuff(const StuffId &id) = 0;
}
class ClientImplementation : public ClientInterface { // not exported
public:
ClientImplementation(Connection *connection);
// +implementation of ClientInterface
}
class ClientFactory {
static ClientInterface *create();
}
Run Code Online (Sandbox Code Playgroud)
有没有理由在这种情况下使用PIMPL?
| 归档时间: |
|
| 查看次数: |
1538 次 |
| 最近记录: |