Qt 自动化测试
Qt 自动化测试
编程思想:先写测试用例,再开发代码
一、修改pro文件
QT += core testlib
二、编写业务类头文件triangle.h
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include <QString>
#include <QObject>
//业务类
class Triangle
{
public:
Triangle();
Triangle(int a, int b, int c);
QString getType();
private:
int m_line1;
int m_line2;
int m_line3;
};
Q_DECLARE_METATYPE(Triangle)
#endif // TRIANGLE_H
三、编写测试类头文件triangletest.h
#ifndef TRIANGLETEST_H
#define TRIANGLETEST_H
#include <QtTest/QtTest>
//测试类
class TriangleTest: public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void case1_type();
void case1_type_data();
};
#endif // TRIANGLETEST_H
四、编写测试类cpp文件triangletest.cpp
#include "triangletest.h"
#include "triangle.h"
void TriangleTest::initTestCase()
{
//init
}
void TriangleTest::case1_type()
{
//取出测试数据
QFETCH(Triangle, triangle);
QFETCH(QString, result);
//测试
QCOMPARE(triangle.getType(), result);
}
void TriangleTest::case1_type_data()
{
//添加列
QTest::addColumn<Triangle>("triangle");
QTest::addColumn<QString>("result");
//输入测试数据
QTest::newRow("test1")<<Triangle(1,1,1)<<"等边三角形";
QTest::newRow("test2")<<Triangle(2,2,1)<<"等腰三角形";
QTest::newRow("test3")<<Triangle(3,4,5)<<"普通三角形";
}
五、编写业务类cpp文件triangle.cpp
#include "triangle.h"
Triangle::Triangle()
{
}
Triangle::Triangle(int a, int b, int c)
{
m_line1 = a;
m_line2 = b;
m_line3 = c;
}
//获取三角形类型
QString Triangle::getType()
{
if(m_line1 == m_line2 && m_line1 == m_line3)
{
return "等边三角形";
}
else if(m_line1 == m_line2 || m_line1 == m_line3 || m_line2 == m_line3)
{
return "等腰三角形";
}
else{
return "普通三角形";
}
}
六、修改main.cpp
#include "triangletest.h"
QTEST_MAIN(TriangleTest)
七、测试正确结果
********* Start testing of TriangleTest *********
Config: Using QtTest library 5.10.1, Qt 5.10.1 (i386-little_endian-ilp32 shared (dynamic) debug build; by GCC 5.3.0)
PASS : TriangleTest::initTestCase()
PASS : TriangleTest::case1_type(test1)
PASS : TriangleTest::case1_type(test2)
PASS : TriangleTest::case1_type(test3)
PASS : TriangleTest::cleanupTestCase()
Totals: 5 passed, 0 failed, 0 skipped, 0 blacklisted, 1ms
********* Finished testing of TriangleTest *********
八、测试错误结果
********* Start testing of TriangleTest *********
Config: Using QtTest library 5.10.1, Qt 5.10.1 (i386-little_endian-ilp32 shared (dynamic) debug build; by GCC 5.3.0)
PASS : TriangleTest::initTestCase()
PASS : TriangleTest::case1_type(test1)
PASS : TriangleTest::case1_type(test2)
FAIL! : TriangleTest::case1_type(test3) Compared values are not the same
Actual (triangle.getType()): "\u666E\u901A\u4E09\u89D2\u5F62"
Expected (result) : "\u76F4\u89D2\u4E09\u89D2\u5F62"
..\TestDemo\triangletest.cpp(15) : failure location
PASS : TriangleTest::cleanupTestCase()
Totals: 4 passed, 1 failed, 0 skipped, 0 blacklisted, 1ms
********* Finished testing of TriangleTest *********
九、总结
在需求不断变化的开发阶段,自动化测试可以最大限度保证程序稳定性,减少bug几率。