如何使用gtest对std :: bind函数进行单元测试? [英] How to unit test the std::bind function using gtest?
问题描述
我正在尝试为项目中的某些cpp文件编写单元测试用例.
I am trying to write unittest cases for some of the cpp files in my project.
这里的场景是: 我有一个cpp文件,其中仅定义了一个公共方法,而后者又调用了私有方法.
The scenario here is: I have a cpp file with only one public method defined and in turn which calls private methods.
在这里,私有方法在公共方法中被称为回调方法.我如何在这里测试私有方法.我将对回调指针进行模拟,但不确定如何调用私有方法.
Here the private methods are called in the public method as a callback method. How do I test the private methods here. I will be doing the mocking for Callback pointer and I am not sure how to call the private method.
请给我一些建议,在这种情况下如何在不更改源代码的情况下调用私有方法.
Please give me some suggestions how to call the private methods in this scenario without changing the source code.
这里是前人:
buttonListenerList <<
sourceButton->addButtonActionCallback(std::bind(&AudioSource::buttonCallback, this, _1, _2));
这种公共的代码是在public方法中定义的.现在,AudioSource::buttonCallback
是私有方法.如何确保通过调用公共方法来调用此私有方法.
This peace of code is defined in the public method. Now the AudioSource::buttonCallback
is a private method. How do you make sure to call this private method by calling the public method.
推荐答案
如果,(您在评论中回答是),可以模拟sourceButton
-然后期望调用addButtonActionCallback
-并存储传递的std::function<>
arg.
If, (you answered yes in comment) sourceButton
can be mocked - then expect addButtonActionCallback
is called - and store the passed std::function<>
arg.
就像下面的示例(用实类型替换...):
Like in the example below (replace ... with real types):
struct TestSuite : public ::testing::Test {
... sourceButtonMock;
std::unique_ptr<...> objectUnderTest;
void SetUp() override;
std::function<...> sourceButtonActionCallback;
};
using namespace ::testing;
void TestSuite::SetUp()
{
EXPECT_CALL(sourceButtonMock, addButtonActionCallback(_))
.WillOnce(SaveArg<0>(&sourceButtonActionCallback);
objectUnderTest = std::make_unique<...>(sourceButtonMock);
}
已将此回调存储在sourceButtonActionCallback
成员变量中-您可以在任意位置随意调用它:
Having stored this callback in sourceButtonActionCallback
member variable - you can call it freely wherever you wish:
TEST_F(TestSuite, shallDo...OnSourceButtonClick)
{
// prerequisites
ASSERT_NE(sourceButtonActionCallback, nullptr);
// Expecteations
...
// action
sourceButtonActionCallback(...);
// post-assertions
...
}
这篇关于如何使用gtest对std :: bind函数进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!