使用单元测试框架进行数据验证



在我们的应用程序中,我们必须设置一个数据验证例程,以应用于我们正在使用的数据集。

更准确地说,对于给定的一组数据,我们希望对其执行一组检查以验证其一致性。例如,给定对象的动态属性,例如:

  • 质量
  • 重心
  • 惯性矩阵

我们想验证:

  • 质量为正
  • 惯性矩阵是对称的
  • 惯性矩阵是确定的正
  • 等。。。

为此,matlab unittest 框架看起来很有趣,因为它提供了一整套检查和验收条件。然而,即使使用参数化测试,似乎也不可能有一个可以接受数据作为输入的测试套件,例如,似乎不可能编写参数化的测试,其中参数是在运行测试套件时设置的,而不是在类中设置的(如文档中所示(。

我想知道我是否缺少有关单元测试 API 的某些内容,或者是否绝对不可能这样做?

我做了一些类似于你问的事情。它不接受命令行参数作为输入,但它实质上是对目录中的一组文件运行测试。下面是一些代码的框架来执行此操作:

classdef checkMyData < matlab.unittest.TestCase
properties(TestParameter)
% just create a cell array of numbers, one for each file, for the test to iterate through
filenum = num2cell(1:length(dir('directorywheredatais*.mat')));
end
methods(Test)
function genericFile(testCase,filenum)
% get details on the file we're currently testing
testDataPath = 'directorywheredatais';
testFiles = dir(fullfile(testDataPath,'*.mat'));
filename = fullfile(testDataPath,testFiles(filenum).name);
[~,nameonly,~] = fileparts(filename);
% load data
load(filename);
% do some test
testCase.verifyGreaterThanOrEqual(mass,[nameonly ': Mass is negative'])
end
end
end

最新更新