【发布时间】:2017-05-30 19:02:28
【问题描述】:
我有不同的测试用例来测试不同的功能。我想在一个 .m 文件和一个测试文件中编写所有不同的函数来检查所有不同的测试用例。
我点击了上面的链接,但我只能看到一个函数实现了 quadraticsolver,但我想实现多个函数以及例如计算正方形、圆形面积的函数。谁能帮我实现多种功能?
【问题讨论】:
标签: matlab unit-testing tdd
我有不同的测试用例来测试不同的功能。我想在一个 .m 文件和一个测试文件中编写所有不同的函数来检查所有不同的测试用例。
我点击了上面的链接,但我只能看到一个函数实现了 quadraticsolver,但我想实现多个函数以及例如计算正方形、圆形面积的函数。谁能帮我实现多种功能?
【问题讨论】:
标签: matlab unit-testing tdd
有关基于函数的测试的更多详细信息,请参阅here。
简单地说,要在同一个 .m 文件中实现多个测试,您需要一个与文件共享名称的主函数,并且该主函数应该聚合文件中的所有本地测试函数(使用 localfunctions)和然后使用functiontests 从这些函数创建一个测试数组。每个本地测试函数都应该接受一个输入(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)
根据上面链接的帮助部分,您还可以创建 setup 和 teardown 函数,分别用作设置和拆卸函数。
更新
根据您的 cmets,如果您现在将所有测试都放在一个文件中,但您希望所有其他功能(您正在测试的功能)也放在一个文件中,您可以但这很重要,请注意,在 .m 文件中定义的任何非主函数的本地函数只能由同一文件中的其他函数访问。 the documentation for local functions有更多信息。
【讨论】:
test_one 和 test_two 是两个不同的测试函数。
quadricSolver.m 文件只是一个普通的.m 文件,您将使用一组测试对其进行测试。如果要添加更多功能,请创建更多.m 文件。如果您使它们成为同一文件的子函数,则它们只能被同一文件中的函数访问。请参阅关于 here 的更详细讨论
如果您有兴趣将相关函数分组到单个内聚文件中,那么您可能希望考虑将您的函数设为类。使用一个类,您可以创建单独的方法,而不是您所说的多个函数。如果你还没有写过很多面向对象的代码,那么这就是你可以在软件中做的许多伟大而美妙(同时也是可怕和可怕)的事情的开始。
例如,您可以这样做(注意这是在三个单独的 *.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。另外,请注意我在这些类中展示了多个函数(属性),但我并没有将所有内容集中在一起。我把它们组合成两个有凝聚力的类。这种凝聚力对于软件设计和保持代码可维护性很重要。
也就是说,这些形状可以按如下方式进行交互:
>> 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
>>
【讨论】: