如何在matlab.unittest.TestCase测试类中跨测试方法共享属性更新值?
在MATLAB单元测试类中跨测试方法共享属性状态
问题说明
需要在matlab.unittest.TestCase子类中声明属性,让一个测试方法修改属性后,后续测试方法能直接使用更新后的值。但当前每个测试方法都会生成独立的测试实例,即使在TestClassSetup中初始化属性,每次运行新测试时属性都会被重置,无法保留前序方法的修改结果。
示例场景代码:
classdef MyTestCase < matlab.unittest.TestCase properties id end % 预期预先设置id = 10 methods(Test) function testMultiplicationByTwo(testCase) testCase.id = testCase.id * 2; testCase.verifyEqual(testCase.id, 20); end function testIdRemainsUnchanged(testCase) testCase.id = testCase.id + 10; % 期望此处id为前序方法修改后的20 testCase.verifyEqual(testCase.id, 30); end end end
可行解决方案
方法1:使用类静态属性
将属性声明为静态属性,属性属于类本身而非单个实例,所有测试实例共享同一值,修改后状态会保留到后续测试。
修改后的完整代码:
classdef MyTestCase < matlab.unittest.TestCase properties(Static) id = 10; % 类级静态属性,所有测试实例共享 end methods(Test) function testMultiplicationByTwo(testCase) MyTestCase.id = MyTestCase.id * 2; testCase.verifyEqual(MyTestCase.id, 20); end function testIdRemainsUnchanged(testCase) MyTestCase.id = MyTestCase.id + 10; testCase.verifyEqual(MyTestCase.id, 30); end end end
方法2:外部持久化变量
通过辅助函数的持久变量存储共享状态,避免直接依赖类静态属性,同样能实现跨测试方法的值共享。
代码示例:
classdef MyTestCase < matlab.unittest.TestCase methods(Test) function testMultiplicationByTwo(testCase) id = getSharedId(); id = id * 2; setSharedId(id); testCase.verifyEqual(id, 20); end function testIdRemainsUnchanged(testCase) id = getSharedId(); id = id + 10; setSharedId(id); testCase.verifyEqual(id, 30); end end end % 辅助函数:读取共享ID function id = getSharedId() persistent storedId; if isempty(storedId) storedId = 10; % 初始化默认值 end id = storedId; end % 辅助函数:更新共享ID function setSharedId(newId) persistent storedId; storedId = newId; end
注意事项
- 测试依赖问题:这种跨测试共享状态的设计会打破单元测试“独立无依赖”的原则,若测试顺序改变,可能导致测试结果不稳定。
- 状态清理:静态属性或持久变量不会自动重置,多次运行测试前,建议在
TestClassTeardown方法中添加重置逻辑,避免影响后续测试。
状态重置示例(针对静态属性)
classdef MyTestCase < matlab.unittest.TestCase properties(Static) id = 10; end methods(TestClassTeardown) function resetSharedId(testCase) MyTestCase.id = 10; % 测试结束后重置初始值 end end methods(Test) function testMultiplicationByTwo(testCase) MyTestCase.id = MyTestCase.id * 2; testCase.verifyEqual(MyTestCase.id, 20); end function testIdRemainsUnchanged(testCase) MyTestCase.id = MyTestCase.id + 10; testCase.verifyEqual(MyTestCase.id, 30); end end end
内容的提问来源于stack exchange,提问作者Назарій Кушнір
相关产品推荐
相关产品推荐

