Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

matlab.unittest.qualifications.Assertable 类

命名空间: matlab.unittest.qualifications

用来确认测试先决条件的验证

描述

Assertable 类提供了一种用来确认测试先决条件的验证机制。除了对失败执行的操作外,Assertable 类与 matlab.unittest.qualifications 包中的其他验证类的工作方式相同。

断言失败时,Assertable 类将引发 AssertionFailedException 对象以告知测试框架发生失败。如果希望通过断言点处的失败来表示当前测试的其余部分无效,但又不想阻止后续测试的正常执行,这种行为会很有用。通常情况下,您可以使用断言来确保符合当前测试的先决条件,或是正确设置了脚手架。如果您不能保证脚手架拆解满足异常安全条件或不能在失败后恢复环境状态,请改用致命断言。

当在 TestCase 类的一个方法中产生断言失败时,该方法的类型确定哪些测试受到影响:

  • Test 方法 - 框架将整个 Test 方法标记为失败和不完整。

  • TestMethodSetupTestMethodTeardown 方法 - 框架将针对该方法实例运行的 Test 方法标记为失败和不完整。

  • TestClassSetupTestClassTeardown 方法 - 框架将整个测试类标记为失败和不完整。

当测试中出现违反先决条件但状态可恢复的情况时,断言可确保使用其余的测试。对于因不满足先决条件而导致失败的情况,它们不执行后续确认,从而防止不必要的失败。如果失败不影响测试的先决条件,也不会导致脚手架设置或拆解问题时,请使用确认,这样可以确保运行完整测试内容。

matlab.unittest.qualifications.Assertable 类是一个 handle 类。

方法

全部展开

事件

事件名称触发器事件数据事件属性
AssertionFailed断言失败时触发。QualificationEventData 对象传递给侦听程序回调函数。matlab.unittest.qualifications.QualificationEventData

NotifyAccess: private

ListenAccess: public

AssertionPassed通过断言时触发。QualificationEventData 对象传递给侦听程序回调函数。matlab.unittest.qualifications.QualificationEventData

NotifyAccess: private

ListenAccess: public

示例

全部折叠

测试写入临时文件夹中的文本文件。使用断言使测试失败,如果无法打开文件,则跳过对文件的写入。

在当前文件夹中名为 TextFileTest.m 的文件中,创建 TextFileTest 类,该类测试将数据写入在临时文件夹中打开的一个文本文件。如果无法打开文件进行写入,则测试失败,并通过使用断言跳过其余测试内容。

classdef TextFileTest < matlab.unittest.TestCase
    methods (Test)
        function testWithTemporaryFolder(testCase)
            folder = testCase.createTemporaryFolder();
            file = fullfile(folder,"myFile.txt");
            fid = fopen(file,"w");
            testCase.addTeardown(@fclose,fid)
            testCase.assertNotEqual(fid,-1,"IO Problem")
            
            txt = repmat("ab",1,1000);
            dataToWrite = join(txt);
            fprintf(fid,"%s",dataToWrite);
            testCase.verifyEqual(string(fileread(file)),dataToWrite)
        end
    end
end

运行 TextFileTest 类。在此示例中,断言通过,测试运行完毕。

runtests("TextFileTest")
Running TextFileTest
.
Done TextFileTest
__________
ans = 
  TestResult with properties:

          Name: 'TextFileTest/testWithTemporaryFolder'
        Passed: 1
        Failed: 0
    Incomplete: 0
      Duration: 0.0467
       Details: [1×1 struct]

Totals:
   1 Passed, 0 Failed, 0 Incomplete.
   0.046653 seconds testing time.

详细信息

全部展开

版本历史记录

在 R2013a 中推出