In the ubuntu system, use QTestLib to do Qt unit testing. Please give me an introductory tutorial example.

I want to use QTestLib to do Qt unit testing on the ubuntu system. Please give me an introductory tutorial example.


Very good, now I will introduce you to the introductory tutorial of using QTestLib for Qt unit testing under Ubuntu system. QTestLib is Qt's own unit testing framework, fully integrated into the Qt environment and easy to use.

We will take Qt Creator as an example and divide it into the following steps:

## 1. Create a new Qt console application

Create a new Qt console application project in Qt Creator (QT5 widgets are not required), select the standard C++ project, and add your own classes and functions to the project.

## 2. Create a new test project

Create a new Qt console application project in the same Qt Creator project (QT5 widgets are not required) and select the test project. The test code files generated here are `main.cpp` and `moc_*.cpp`.

## 3. Test basics

Code testing usually involves the following issues:

- How to ensure consistency and repeatability of test cases?
- How to set up and clear the test environment?
- How to capture and report test failures?

The QTestLib framework provides some mechanisms to address these issues:

#### 3.1. Test case consistency

QTestLib provides the `QTest::qExec()` function, in which all test cases are run, as shown below:

```cpp
int main(int argc, char *argv[])
{     QApplication app(argc, argv);     MyTest test; // Create a new test class     return QTest::qExec(&test, argc, argv); // Run all test case } ```




The first parameter of the `QTest::qExec()` function is the pointer of the test class, pointing to the object `test` of our test class, and the second and third parameters are the standard parameters of the `main()` function. Through the `QTest::qExec()` function, all test cases can be run and the results exported to the application's standard output for analysis and reporting.

#### 3.2. Setting up and clearing the test environment

QTestLib can set up and clear the test environment before testing in two ways:

- setUp() and tearDown() functions: set and clear the test environment before and after testing respectively.

For example, the following two test functions are defined in the test class:

```cpp
class MyTest : public QObject
{
    Q_OBJECT
public slots:
    void testAddition()
    {
        ...
    }

    void testSubtraction()
    {
        ...
    }

private:
    int m_value;
};

```

We can use the `setUp()` function to set up the test environment before the test starts, and use the `tearDown()` function to clear the test environment after the test ends. As follows:

```cpp
class MyTest : public QObject
{
public:
    MyTest();

private slots:
    void initTestCase(); // Define the function before the test
    void cleanupTestCase(); // Define the function after the test ends

    void testAddition();
    void testSubtraction();

private:
    int m_value;
};

void MyTest::initTestCase()
{
    m_value = 0;
}

void MyTest::cleanupTestCase()
{
}

void MyTest::testAddition()
{     m_value = 2 + 2;     QVERIFY(m_value == 4); // Assert, whether it is true }


void MyTest::testSubtraction()
{     m_value = 5 - 3;     QVERIFY(m_value == 2); // Assert, whether it is true } ```



When testing starts, QTestLib will call the `initTestCase()` function, where we can set up the test environment. After the test, QTestLib calls the `cleanupTestCase()` function, where we can clear the test environment.

- Predefined functions: QTestLib also provides some predefined test functions, which are executed before the test starts or after the test ends.

For example, in the `main()` function, we can use the `QTest::qExec()` function to execute the test while setting up and clearing the test environment as follows:

```cpp
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    return QTest::qExec(new MyTest, argc, argv);
}
```

The first parameter of the `QTest::qExec()` function is the pointer of the test class, pointing to the object `test` of our test class, and the second and third parameters are the standard parameters of the `main()` function. Through the `QTest::qExec()` function, all test cases can be run and the results exported to the application's standard output for analysis and reporting.

#### 3.3. Handling test exceptions

QTestLib throws an exception when a test case fails. We can assert test results using the following macro definitions within test cases, such as `QVERIFY()` and `QCOMPARE()`:

- `QVERIFY()`: used to verify that the result of an expression is true.
- `QCOMPARE()`: used to verify that the values ​​of two expressions are equal.

If the result of the expression is false or the two values ​​are not equal, a `QTest::qFail(const char *message, const char *file, int line)` exception will be thrown and the test case will fail.

```cpp
void MyTest::testSubtraction()
{     m_value = 5 - 3;     QVERIFY(m_value == 2); // Assert: whether m_value is equal to 2 } ```



If the assertion fails, QTestLib will output failure information and throw an exception, and the test case will fail.

## 4. Use QTestLib for testing

Here is an example showing how to use QTestLib for a simple test:

```cpp
#include <QtTest/QtTest>
#include "mymath.h"

class MyTest : public QObject
{     Q_OBJECT private slots:     void     Unfortunately, it is not complete and may exceed the interface reply text length.     Question again:     Please give an example that shows how to use QTestLib for simple unit testing:     Okay, here is an example of using QTestLib for simple unit testing:



    


    
    
    

    
    

```c++
#include <QtTest>

class TestMath : public QObject
{
    Q_OBJECT

public:
    TestMath() {}

private slots:
    void testAddition()
    {
        int result = 1 + 2;
        QVERIFY(result == 3);
    }

    void testSubtraction()
    {
        int result = 5 - 3;
        QCOMPARE(result, 2);
    }

    void testMultiplication()
    {
        int result = 4 * 2;
        QVERIFY2(result == 8, "Failed: result is not equal to 8");
    }
};

QTEST_APPLESS_MAIN(TestMath)
#include "testmath.moc"
```

In this example, we create a test class called TestMath and declare three test functions in it: testAddition, testSubtraction, and testMultiplication. In each test function, we perform some calculations and use the QVERIFY, QVERIFY2, and QCOMPARE macros to verify that the results are correct.

The QVERIFY and QVERIFY2 macros respectively determine whether an expression is true. If it is false, the test fails and an error message is printed. The QCOMPARE macro compares the values ​​of two expressions for equality. If they are not equal, the test fails and an error message is output.

Finally, we use the QTEST_APPLESS_MAIN macro to define the entry point of the test application and introduce the testmath.moc file to support test classes using QObject.

The following is sample code for simple unit testing using QTestLib.

## 1. Create project

First, open Qt Creator and create a new Qt console application project: select "File" > "New File or Project", select "Non-Qt Project" > "Plain C++ Project", enter the name, project path and a certain available compilers and click Next.

On the "Kit Selection" page, select "Desktop Qt 5.xx GCC 64-bit" or any available Qt 5 Kit, and click "Next".

On the "Project Management" page, uncheck the "Create Main Function" option, enter the "TestProject" name, and click "Next".

On the "Project Configuration" page, select "None" for the "Version Control" and click "Finish".

At this point, the project has been created successfully.

## 2. Add QTestLib library

In the project's `TestProject.pro` file, add the following lines:

```pro
QT += testlib
CONFIG += console
```

This will contain the QTest class and test library dependencies for use with the application.

## 3. Write test cases

Create a new source file `testexample.cpp` in the "Project" folder and write test cases. Here is an example:

```cpp
#include <QtTest/QtTest>

// This unit test will test whether ints are equal
class TestExample: public QObject
{     Q_OBJECT

private slots:
    void simpleTest()
    {         int x = 1;         QCOMPARE(x, 1); // Expect x value to be 1     }


    void nullTest()
    {         void* p = 0;         QVERIFY(!p); // Expect p value to be 0     } }; ```




As you can see, a `TestExample` class is defined here, which contains two test cases: the first test case checks whether `x` is equal to `1`, and the second test case checks whether a pointer is null.

Use the QTest macros `QCOMPARE` and `QVERIFY` to compare results.

## 4. Activate automatic testing

QTest uses a macro `QTEST_APPLESS_MAIN` to automatically run test cases. Just create a "main.cpp" file and activate the macro using the following code.

```cpp
#include <QTest>

QTEST_APPLESS_MAIN(TestExample)
```

At this point, you can find the text "PASS: 2 Test" in the "Compile Output" panel of Qt Creator. This means that both test cases passed successfully.

If a test case does not pass successfully, you can find more information in the "Compile Output" panel in Qt Creator.

The following is an example of simple testing using QTestLib.

Suppose we have a simple calculator program, tested using QTestLib.

## 1. Write test cases

Create a file named `CalculatorTest.h` and write the test cases. Here is an example:

```cpp
#include <QtTest/QtTest>
#include "Calculator.h"

class CalculatorTest : public QObject {
    Q_OBJECT
private slots:
    void testAddition();
    void testSubtraction();
    void testMultiplication();
    void testDivision_data();
    void testDivision();
};

void CalculatorTest::testAddition() {
    Calculator calculator;
    QCOMPARE(calculator.addition(2, 2), 4);
    QCOMPARE(calculator.addition(0, 0), 0);
    QCOMPARE(calculator.addition(-1, 1), 0);
}

void CalculatorTest::testSubtraction() {
    Calculator calculator;
    QCOMPARE(calculator.subtraction(2, 2), 0);
    QCOMPARE(calculator.subtraction(0, 0), 0);
    QCOMPARE(calculator.subtraction(-1, 1), -2);
}

void CalculatorTest::testMultiplication() {
    Calculator calculator;
    QCOMPARE(calculator.multiplication(2, 2), 4);
    QCOMPARE(calculator.multiplication(0, 0), 0);
    QCOMPARE(calculator.multiplication(-1, 1), -1);
}

void CalculatorTest::testDivision_data() {
    QTest::addColumn<int>("nominator");
    QTest::addColumn<int>("denominator");
    QTest::addColumn<int>("quotient");
    QTest::addColumn<bool>("exception");

    QTest::newRow("Valid case 1") << 4 << 2 << 2 << false;
    QTest::newRow("Valid case 2") << 0 << 4 << 0 << false;
    QTest::newRow("Valid case 3") << 1 << -1 << -1 << false;
    QTest::newRow("Invalid case") << 4 << 0 << 0 << true;
}

void CalculatorTest::testDivision() {
    Calculator calculator;
    QFETCH(int, nominator);
    QFETCH(int, denominator);
    QFETCH(int, quotient);
    QFETCH(bool, exception);

    if (exception) {
        QVERIFY_EXCEPTION_THROWN(calculator.division(nominator, denominator), std::runtime_error);
    } else {
        QCOMPARE(calculator.division(nominator, denominator), quotient);
    }
}

QTEST_APPLESS_MAIN(CalculatorTest)
#include "CalculatorTest.moc"
```

Each test case is a `void` function, and we use the `QCOMPARE()` macro to determine whether the actual output value is consistent with the expected value.

In the above code, we used the `Q_TEST_MAIN` macro, indicating that there is no need to automatically generate the main function, and passed in the test class name `CalculatorTest`, and also used the data-driven approach (`testDivision_data()` and `testDivision( )` function) to complete tests involving multiple data sets.

## 2. Compile and run tests

In the command line, enter the project root directory and enter the following command to compile:

```bash
qmake -project
qmake
make
```

At the command line, enter the following command to run the test:

```bash
./CalculatorTest
```

At the command line, you can see output similar to the following:

```bash
********* Start testing of CalculatorTest *********
Config: Using QtTest library 5.15.2, Qt 5.15.2 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 8.3.0)
PASS   : CalculatorTest::initTestCase()
PASS   : CalculatorTest::testAddition()
PASS   : CalculatorTest::testDivision("Invalid case")
PASS   : CalculatorTest::testDivision("Valid case 1")
PASS   : CalculatorTest::testDivision("Valid case 2")
PASS   : CalculatorTest::testDivision("Valid case 3")
PASS   : CalculatorTest::testMultiplication()
PASS   : CalculatorTest::testSubtraction()
PASS   : CalculatorTest::cleanupTestCase()
Totals: 9 passed, 0 failed, 0 skipped, 0 blacklisted, 37ms
********* Finished testing of CalculatorTest *********
```

The above is an example of using QTestLib for simple testing. If you have any other questions or concerns, please feel free to ask. 

 

Supongo que te gusta

Origin blog.csdn.net/thanklife/article/details/130238510
Recomendado
Clasificación