如何在 Matlab 中的单个文件中编写多个测试函数(TDD 实现)

How to write multiple test functions in a single file in Matlab (TDD implementation)

我有不同的测试用例来测试不同的功能。我想在一个.m文件和一个测试文件中编写所有不同的功能来检查所有不同的测试用例。

https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html#zmw57dd0e66668

我遵循了上面的 link 但我只能看到一个函数实现了 quadraticssolver 但我想实现多个函数以及例如计算正方形,圆的面积。谁能帮我实现多个功能?

有关 function-based 测试的更多详细信息,请参见 here

简而言之,要在同一个 .m 文件中实现多个测试,您将需要一个与文件共享名称的主函数,并且该主函数应聚合文件中的所有本地测试函数(使用 localfunctions) and then create an array of tests from these functions using functiontests. Each local test function should accept one input (a matlab.unittest.TestCase 对象).

my_tests.m

function tests = my_tests()
    tests = functiontests(localfunctions);
end

% One test
function test_one(testCase)
    testCase.assertTrue(true)
end

% Another test
function test_two(testCase)
    testCase.assertFalse(true);
end

然后为了 运行 这些测试,您需要使用 runtests 并传递文件名或使用 run 并传递函数的输出。

runtests('my_tests.m')
% or 
run(my_tests)

根据上面链接的帮助部分,您还可以创建 setupteardown 函数,分别用作设置函数和拆卸函数。

更新

根据您的评论,如果您现在将所有测试都放在一个文件中,但您希望所有其他功能(您正在测试的功能)也放在一个文件中,您可以 执行此操作,但重要的是要注意,在 .m 文件中定义的任何不是主函数的局部函数只能由同一文件中的其他函数 访问。 the documentation for local functions.

中有更多信息

如果您有兴趣将相关函数分组到一个单一的内聚文件中,那么您可能需要考虑将您的函数设为 class。使用 class 您可以创建单独的方法,而不是像您所说的那样创建多个函数。如果您还没有写过很多面向对象的代码,那么这就是您可以在软件中做的许多伟大而美妙(也令人恐惧和可怕)事情的开始。

例如,您可以这样做(注意这是在三个单独的 *.m 文件中):

% Shape.m
classdef Shape
    properties(Abstract)
        Area
        Circumference
    end
end

% Circle.m
classdef Circle < Shape
    properties(Dependent)
        Area
        Circumference
    end
    properties
        Radius
    end

    methods
        function circle = Circle(radius)
            circle.Radius = radius;
        end
        function area = get.Area(circle)
            area = pi*circle.Radius^2;
        end
        function circumference = get.Circumference(circle)
            circumference = 2*pi*circle.Radius;
        end
    end
end

% Rectangle.m
classdef Rectangle < Shape
    properties(Dependent)
        Area
        Circumference
    end
    properties
        Length
        Height
    end

    methods
        function rectangle = Rectangle(length, height)
            rectangle.Length = length;
            rectangle.Height = height;
        end
        function area = get.Area(rectangle)
            area = rectangle.Length*rectangle.Height;
        end
        function circumference = get.Circumference(rectangle)
            circumference = 2*(rectangle.Length+rectangle.Height);
        end
    end
end        

注意我展示了多个属性的使用,但由于它们是依赖的,所以它们实际上就像函数一样。每次您请求 属性 时,函数 get.PropertyName 就像函数一样被调用。另外请注意,我在这些 class 中展示了多个函数(属性),但我并没有将所有内容都集中在一起。我将它们组合成两个有凝聚力的 classes。这种凝聚力对于软件设计和保持代码的可维护性很重要。

也就是说,这些形状可以按如下方式进行交互:

>> c = Circle(5);
>> c.Area % calls the get.Area "function"

ans =

   78.5398

>> c.Circumference

ans =

   31.4159

>> r = Rectangle(4,5);
>> r.Area

ans =

    20

>> r.Circumference

ans =

    18

>> 

开始使用 here and here