模拟对象的困境

发布于 2024-12-19 05:42:47 字数 737 浏览 2 评论 0原文

我们遇到以下问题:许多我们无法触及但需要对它们进行单元测试的类,不幸的是,这些类在设计时并未考虑到单元测试,因此我们创建模拟对象来测试代码。

示例:

class SomeOtherClass
{
public:
void foo2() {  … }
};

class ClassToTest
{
public:
ClassToTest() {…}
void foo1() { SomeOtherClass A.foo2(); }
};

在上面的示例中,我们想要测试 foo1() 但它需要 foo2(),因此我们想要创建 foo2()属于模拟对象(在现实生活中,这些函数/类要复杂得多,并且涉及与硬件配置等的交互,因此需要模拟对象/函数)。

到目前为止,我们已经做了类似的事情,但它确实不是最佳的,因为代码似乎对其他单元测试有副作用。

class MockSomeOtherClass
{
public:
  foo2() { … } // mock function
};

#define SomeOtherClass MockSomeOtherClass

#include “ClassToTest.cpp”
...

有没有更好的方法可以在不更改原始类(或进行最小更改)的情况下做到这一点?我们使用 CPPUnit 进行测试。

编辑:添加标签 winapi 以更清楚地描述环境。

We have the following problem: a number of classes that we cannot touch but need to unit test them unfortunately the classes are not designed with unit testing in mind so we issues creating mock objects to test the code.

Example:

class SomeOtherClass
{
public:
void foo2() {  … }
};

class ClassToTest
{
public:
ClassToTest() {…}
void foo1() { SomeOtherClass A.foo2(); }
};

In the above example we would like to test foo1() but it needs foo2() so we would like to make foo2() belong to a mock object (in real life these functions/classes are vastly more complex and involve interaction with hardware configurations etc thus the need for mock objects/functions).

Until now we have done something like this but it is really not optimal because the code seems to have side effects on other unit tests.

class MockSomeOtherClass
{
public:
  foo2() { … } // mock function
};

#define SomeOtherClass MockSomeOtherClass

#include “ClassToTest.cpp”
...

Is there a better way to do this without changing the original classes (or with minimal changes)? We use CPPUnit for testing.

EDIT: added tag winapi to more clearly describe out environment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿忘心安 2024-12-26 05:42:47

有一个名为 Typemock Isolator++ 的产品似乎可以解决您提出的问题。我还没有尝试过,所以无法评论它的效果如何或使用起来有多容易/困难。

不幸的是,您必须向他们提供您的电子邮件地址才能尝试。下载非常简单,但是您会被重定向到此页面,它会愉快地引导您“立即注册您的软件即可免费试用!请输入您的详细信息(包括有效的电子邮件),以便接收激活密钥以开始使用 Isolator++。”

There is a product called Typemock Isolator++ that appears to address the issues you have raised. I have not tried it yet, so can't comment on how well it works or how easy/difficult it is to use.

Unfortunately, you have to give them your email address to try it. The download is easy enough, but then you are redirected to this page which cheerfully directs you to "Register your software now to get a FREE trial! Please enter your details including a valid email in order to receive your activation key to start using Isolator++."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文