方法和模拟同一个类
我有两个方法的类,
class A
{
void Fun()
{
if(FunRet()>0){///} else {///}
}
int FunRet()
{ return 4;}
};
我想根据 FunRet 返回的内容来测试 Fun() 方法。所以我想嘲笑 FunRet。 我不想让 FunRet 成为虚拟的。我怎样才能做到这一点?
I have class with 2 methods
class A
{
void Fun()
{
if(FunRet()>0){///} else {///}
}
int FunRet()
{ return 4;}
};
I want to test Fun() method depend on what FunRet returns. So i want to mock FunRet.
I rather don't want make FunRet as virtual. How I can do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以注入类内依赖项。在这种情况下,让 Fun 接受一个值而不是计算它:
然后您的测试可以将任意值传递到 Fun() 中。如果您需要强制正确使用,请编写一个公共版本以在您的 API 中公开,并编写一个私有版本以进行测试:
You can inject intra-class dependencies. In this case, make Fun accept a value instead of computing it:
Then your tests can pass arbitrary values into Fun(). If you need to enforce correct use, write a public version to expose in your API and a private version for testing:
您可以将 Fun 方法提取到实现接口的计算器类中。您应该在构造函数中将该接口的实例传递给 A 类。
在测试中,您可以让其他类实现该接口,并返回其他值。
此方法还有一个很大的优点,即您可以将计算值和使用计算值的关注点分开。
You could extract the Fun method into a calculator class that implements an interface. You should pass an instance of that interface to class A at constructor.
In testing you could have other classes implementing that interface, that return other values.
This method also have the big advantage, that you seperate the concerns of calculating a value and using the calculated value.
我认为你错过了 this 指针。
... if ( this->FunRet() > 0 ) { ...
I think you're missing the this pointer.
... if ( this->FunRet() > 0 ) { ...
如果您使用依赖项注入并对被测对象进行模板化,则可以使用模拟对象而不必使用虚函数。
If you use dependency injection and template your object under test, you can use mock objects without having to use virtual functions.
我相信
FunRet
是Fun
的内部实现细节。因此,Fun
不需要与FunRet
分开进行测试。只需测试Fun
而不必担心它调用FunRet
的事实。I believe
FunRet
is an internal implementation detail ofFun
. As a result,Fun
does not need to be tested in isolation fromFunRet
. Just testFun
and don't worry about the fact it callsFunRet
.