一、单元测试是什么

驱动代码是用于调用被测试单元的代码,它提供了测试输入并捕获输出结果。桩代码是用于模拟被测试单元所依赖的其他组件或模块的代码,以便在测试过程中隔离被测试单元。模拟代码是用于模拟外部依赖的行为,以便在测试过程中控制和验证被测试单元的交互。

二、单元测试的过程

  1. 确定要测试的单元:选择一个具体的类或函数作为测试的目标。
  2. 编写测试用例:根据被测试单元的功能和逻辑编写多个测试用例,覆盖不同的输入和边界情况。
  3. 编写测试代码:使用适当的测试框架编写测试代码,包括调用被测试单元并验证输出结果的断言。
  4. 运行测试:运行测试代码,确保所有的测试用例都能通过。
  5. 分析结果:检查测试结果,查找失败的测试用例并修复相关问题。
  6. 重复上述步骤:持续编写和运行测试,直到所有的测试用例都能够通过。

三、为什么需要单元测试

  1. 确保代码质量:单元测试可以帮助开发者验证代码的正确性,确保代码按照预期工作。通过编写针对每个函数或方法的单元测试,可以及早发现潜在的问题和错误,从而提高代码的质量。

  2. 提高代码可维护性:单元测试可以作为代码的文档,帮助开发者理解和维护代码。当需要修改代码时,可以通过运行单元测试来验证修改是否影响了代码的正确性。

  3. 支持重构和优化:单元测试可以在重构和优化代码时提供保障。通过运行单元测试,可以确保重构和优化后的代码仍然按照预期工作,避免引入新的问题。

  4. 提高开发效率:虽然编写单元测试需要一定的时间和精力,但它可以帮助开发者在后期节省大量的调试时间。通过及早发现和解决问题,可以减少调试的时间和精力,提高开发效率。

  5. 支持持续集成和自动化测试:单元测试是持续集成和自动化测试的基础。通过编写可自动运行的单元测试,可以在每次代码提交后自动运行测试,及早发现问题,确保代码的稳定性和可靠性。

四、MQL测试代码实现

#property link          "VX: mtquant"
#property version		"1.10"
#property description   "MQL语言的一个简单的单元测试工具。."

#define assert_equal(v_1, v_2) _assert_equal(__FILE__, __FUNCTION__, (string)__LINE__, (v_1), (v_2))

class TestCase 
{
    protected:
        string errors[];
        uint   error_len;

        uint   tests_number;
        uint   successful_tests_number;

        uint   start_time;

        // changed parameters
        string output_file_path;
    public:
        TestCase() 
        {
            error_len = 0;
            tests_number = 0;
            successful_tests_number = 0;
            output_file_path = MQLInfoString(MQL_PROGRAM_NAME) + "_unit_test_log.txt";
            start_time = GetTickCount();
        }
        //
        void set_output_file_path(string _output_file_name)
        {
            output_file_path = _output_file_name;
        };
        //
        void add_error(string error) 
        {
            error_len++;
            ArrayResize(errors, error_len);
            errors[error_len-1] = error;
        }
        //
        template<typename T1,typename T2>
            void _assert_equal(string file, string func_sig, string line, T1 v_1, T2 v_2)
            {
                tests_number++;
                // ex: TestFunc.mq4(38), MyTest::test_string_len(): 11 != 5
                if (v_1 != v_2) 
                    add_error(file + "(" + line + "), " + func_sig + "(): " + (string)v_1 + " != " + (string)v_2);
                else
                    successful_tests_number++;
            }
        //
        string pretty_time(int ms) 
        {
            return (string)(ms/1000) + " sec";
        }
        //
        bool check_file(int h_file) 
        {
            if (h_file < 0) 
            {
                Comment(output_file_path + ": Error with file creation (error: " + (string)GetLastError() + ")");
                return false;
            }

            return true;
        }
        //
        bool init_log_file() 
        {
            int handle = FileOpen(output_file_path, FILE_WRITE, ";");
            if (!check_file(handle)) return false;

            FileWrite(handle, StringFormat("--- %s: Unit Test: running... ---", TimeToString(TimeLocal())));
            FileClose(handle);

            return true;
        }
        //
        virtual void declare_tests(){}
        //
        void run()
        {
            if (!init_log_file()) return;

            declare_tests();

            // write log
            int handle = FileOpen(output_file_path, FILE_WRITE, ";");

            if (check_file(handle)) 
            {
                FileWrite(handle, StringFormat("--- %s: Unit Test: passed tests %d from %d (elapsed time: %s) ---",
                            TimeToString(TimeLocal()), successful_tests_number, tests_number, pretty_time(GetTickCount() - start_time)));

                for (uint i=0;i<error_len;i++)
                    FileWrite(handle, errors[i]);

                FileClose(handle);
            }
        }
};
class SimpleTest: public TestCase 
{
    void test_math_abs() 
    {
        assert_equal(MathAbs(-1.25), 1.25);
        assert_equal(MathAbs(2.15), 2.15);
    }

    void test_string_len() 
    {
        assert_equal(StringLen("xxx"), 3);
        assert_equal(StringLen("some string"), 5);  // test fails
    }

    void declare_tests() 
    {
        test_math_abs();
        test_string_len();
    }
};


double min(double v_1, double v_2) 
{
    if (v_1 > v_2) return v_2;

    return v_1;
}


class MyFunctionTest: public TestCase 
{
    void test_my_function_min() 
    {
        assert_equal(min(4, 10), 4);
        assert_equal(min(8, 1), 1);
        assert_equal(min(5, 0), 5);  // test fails
    }

    void declare_tests() 
    {
        test_my_function_min();
    }
};

void OnStart() 
{
    SimpleTest simple_test;
    simple_test.run();

    MyFunctionTest my_function_test;
    my_function_test.set_output_file_path(MQLInfoString(MQL_PROGRAM_NAME) + "_MyFunctionTest_unit_test.log");  // long name
    my_function_test.run();
}

02-23 12:11