对于gtest,如何模拟名称相同但类型不同的方法 [英] For gtest, how to mock methods which have the same name, but different types
问题描述
我使用Gtest验证我的C ++代码,现在我遇到了模拟问题.由于多种原因,我有一些方法,它们的名称相同,但是类型参数和实现不同,例如
I use Gtest to verify my C++ code, and now I face a mocking problem. For several reasons, I have some methods, which have the same name, but different type arguments and implementation, like
void foo(int& i);
void foo(double& d);
void foo(float& f);
对他们来说,我制作了模拟方法,例如
For them, I make mock methods, like
MOCK_METHOD1(foo, void(int&));
MOCK_METHOD1(foo, void(double&));
MOCK_METHOD1(foo, void(float&));
但是,我无法为他们使用EXPECT_CALL.在测试代码中,我为foo(int)设置了操作,例如
However, I could not use EXPECT_CALL for them. In a test code, I set action for foo(int), like
EXPECT_CALL(mock_object, foo(_)).WillOnce(DoAll(SetArgReferee<0>(10),Return()));
但是,编译器失败,因为int,double和float之间的目标不明确.
but, compiler failed because target is ambiguous among int, double and float.
是否可以将EXPECT_CALL用于特定类型的模拟方法?
Is there any way to use EXPECT_CALL for specific type mock method?
我无法使用testing :: MatcherCast和testing :: SafeMatcherCast,因为它们仅接受const类型.但是,我需要更新参数,因此无法使用const.
I failed to use testing::MatcherCast and testing::SafeMatcherCast, because they only accept const type. However, I need to update the argument, so I could not use const.
推荐答案
You can use typed wildcard (documentation):
EXPECT_CALL(mock_object, foo(An<int&>())).WillOnce(SetArgReferee<0>(10));
EXPECT_CALL(mock_object, foo(A<double&>())).WillOnce(SetArgReferee<0>(10.));
A<>
和 An<>
的含义完全相同,它们有两个名称,目的是为了更好地阅读.在 godbolt
A<>
and An<>
mean exactly the same, they have two names just for nicer reading.
See it online on godbolt
旁注:您不必通过 void
方法进行 Return()
.
Side note: You don't have to Return()
from void
method.
这篇关于对于gtest,如何模拟名称相同但类型不同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!