In7*_*n78 5 c++ python mocking pybind11
我正在使用 pybind11 为某些 C++ 代码实现 python 绑定。现在我正在尝试为绑定编写单元测试。
class A在 C++ 中有一个像这样的构造函数:
class A
{
A(std::unique_ptr<B> B_ptr);
}
Run Code Online (Sandbox Code Playgroud)
它接受 aunique_ptr到 的对象class B。class B是一个可以派生的抽象基类。我编写了class B可以从 Python 派生的绑定。是否有可能创建unittest.mock用于派生的 Python 模拟,class B以便A在其构造函数中接受模拟?
模拟可以有一个spec定义的时间,它们可以从中借用报告的类(以及许多其他基本行为)。因此,最简单的方法是:
mymock = Mock(spec=B()) # Mock borrows behaviors of this instance of B, including class
Run Code Online (Sandbox Code Playgroud)
如果不想使用spec(它有很多其他副作用),可以对报告的类进行有针对性的修改。Mocks 有一个可分配的__class__属性,因此这将产生一个空白,将Mock其自身报告为 的子类B:
mymock = Mock()
mymock.__class__ = B
Run Code Online (Sandbox Code Playgroud)