c++ stub模式实例
时间: 2023-08-11 14:44:03 浏览: 64
C++中的Stub模式通常用于测试和模拟。下面是一个简单的示例:
假设我们有一个名为`Calculator`的类,其中有一个`add`方法用于将两个数字相加并返回结果。我们想要编写一个测试程序来测试`Calculator`类的`add`方法,但是我们不想实际执行`add`方法,而是想使用一个模拟的`add`方法来测试它。这就是Stub模式派上用场的地方。
首先,我们需要创建一个`Calculator`类的接口,并在其中声明`add`方法:
```cpp
class CalculatorInterface {
public:
virtual int add(int a, int b) = 0;
};
```
接下来,我们需要创建一个名为`CalculatorStub`的类来实现`CalculatorInterface`接口,并实现`add`方法。在这个类中,我们只需要返回一个预先定义好的结果,而不必实际执行`add`方法:
```cpp
class CalculatorStub : public CalculatorInterface {
public:
int add(int a, int b) override {
return 10; // 返回预定义的结果
}
};
```
现在,我们可以创建一个测试程序来测试`Calculator`类的`add`方法。在测试程序中,我们可以使用`CalculatorStub`类来代替`Calculator`类的实际实现,并将其传递给测试函数:
```cpp
#include <iostream>
void testCalculator(CalculatorInterface& calculator) {
int result = calculator.add(5, 5);
if (result == 10) {
std::cout << "Test passed." << std::endl;
} else {
std::cout << "Test failed." << std::endl;
}
}
int main() {
CalculatorStub calculatorStub;
testCalculator(calculatorStub);
return 0;
}
```
在上面的示例中,我们创建了一个`CalculatorStub`对象,并将其传递给`testCalculator`函数。在`testCalculator`函数中,我们调用了`CalculatorInterface`接口的`add`方法,并检查其返回值是否等于预期的结果。
这就是一个简单的C++ Stub模式示例。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)