我有不同的测试用例来测试不同的功能。我想在一个.m文件和一个测试文件中编写所有不同的函数来检查所有不同的测试用例。
我按照上面的链接但是我只能看到一个函数实现了quadraticsolver但是我想实现多个函数以及例如计算方形,圆形区域。任何人都可以帮助我实现多种功能吗?
答案 0 :(得分:3)
可以找到有关基于功能的测试的更详细信息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
功能。
<强>更新强>
根据您的评论,如果您现在所有测试都在一个文件中,但您希望所有其他功能(您正在测试的功能)也在一个文件中,那么可以做但重要的是要注意,.m文件中定义的不是主函数的任何本地函数只能被同一文件中的其他函数访问。 the documentation for local functions中有更多信息。
答案 1 :(得分:2)
如果您有兴趣将相关功能分组到一个有凝聚力的文件中,那么您可能需要考虑使您的功能成为一个类。使用类可以创建单独的方法,而不是像你说的那样创建多个函数。如果你还没有编写很多面向对象的代码,那么这就是你可以在软件中做的许多伟大而精彩(以及可怕和可怕)的事情的开始。
例如,您可以执行以下操作(请注意,这是在三个单独的* .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
注意我展示了使用多个属性,但由于它们是依赖的,它们实际上就像函数一样。每次你要求属性得到函数。 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
>>