我目前正在设置一个单元测试助手类,它在Qt中使用C++11验证信号是否在测试期间发出,与其顺序无关,例如:
void TestUtils::verifyVolumeAdjustment(const QSignalSpy &vol_spy, uint percent)
{
for(QList<QVariant> vol_call_args : vol_spy){
if(vol_call_args.at(0).toInt() == percent)
{
return;
}
}
QString err = QString("volume never set to %1").arg(QString::number(percent));
QFAIL(err.toLocal8Bit().constData());
}我有十几个这样的函数,都是用来检查是否发出了某些信号。现在我需要编写顺序很重要的测试。在这些测试中,我需要进行验证,例如:
Volume set to 10
Volume set to 50但完全是按照这个顺序。现在我的问题是,是否有一种方法可以使用可变模板或类似的方法来将函数调用列表传递给函数。我将通用的顺序检查函数想象为如下所示:
void checkExecutionOrder(const QSignalSpy& spy, FunctionCallList call_list){
for(int i = 0; i < call_list.length(), i++){
QSignalSpy temp;
temp.append(spy.at(i)); //create a temporary copy of that caught signal to ensure its the only thing validated
call_list[i].call(temp, arguments); // call the function from the list with modified spy and remaining arguments
}
}有什么好的方法可以做到这一点,这样我就不必为每个函数创建顺序敏感的测试函数了吗?
发布于 2020-08-25 16:00:33
另一种选择是使用lambdas。下面是如何实现的:
for
std::functions
void myFooFunction(QVector<std::function<int(int)>>& myVec)
{
for(auto& x:myVec)
{
x(1);
}
}
int main(int argc, char* argv[])
{
QVector<std::function<int(int)>> x;
auto f1 = [](int x){qDebug() << "x ++" << x; return x++;};
auto f2 = [](int x){qDebug() << "x --" << x; return x--;};
x.push_back(f1);
x.push_back(f2);
myFooFunction(x);发布于 2020-08-25 15:59:19
可以使用std::vector和std::function将具有相同签名的函数列表传递给checkExecutionOrder
#include <vector>
#include <functional>
using FunctionCall = std::function< void(int,int) >;
using FunctionCallList = std::vector<FunctionCall>;
void checkExecutionOrder(FunctionCallList call_list){
for (auto f : call_list) {
f(42,42);
}
}
void foo(int x,int y){}
int main() {
checkExecutionOrder( { foo,foo } );
}https://stackoverflow.com/questions/63574285
复制相似问题