如何让QCumber测试中expect块识别before块定义的变量?
解决QCumber中before块变量无法在expect块识别的问题
核心原因
QCumber的before块与expect块拥有独立作用域,直接在before内定义的局部变量不会自动暴露给后续测试块,必须通过框架提供的上下文机制实现变量共享。
解决方案
方法1:使用this上下文存储变量
在before块中将变量绑定到测试实例的this对象,expect块通过this访问共享变量,这是QCumber推荐的标准方式:
before:{ this.inputData: 1.0 2.0 3.0 4.0 5.0; this.period: 2; this.expectedOutput: 0n 1.5 2.5 3.5 4.5; }; expect:{ actualOutput: src.ti.sma[this.period; this.inputData]; actualOutput ~ this.expectedOutput; };
方法2:通过before返回字典,expect接收参数
让before块返回包含变量的字典,expect块以参数形式接收该字典:
before:{ inputData: 1.0 2.0 3.0 4.0 5.0; period: 2; expectedOutput: 0n 1.5 2.5 3.5 4.5; `inputData`period`expectedOutput!inputData period expectedOutput; }; expect:{ctx| actualOutput: src.ti.sma[ctx.period; ctx.inputData]; actualOutput ~ ctx.expectedOutput; };
方法3:全局变量(不推荐)
将变量定义为全局命名空间下的变量,虽然能解决识别问题,但会污染全局环境,仅适合临时测试场景:
before:{ .inputData: 1.0 2.0 3.0 4.0 5.0; .period: 2; .expectedOutput: 0n 1.5 2.5 3.5 4.5; }; expect:{ actualOutput: src.ti.sma[.period; .inputData]; actualOutput ~ .expectedOutput; };
额外验证要点
- 确保测试环境已正确加载
src/ti.q,可在测试文件开头添加\l src/ti.q,或通过QCumber配置指定依赖文件路径。 - 检查变量类型与维度是否匹配
sma函数要求,比如period需为整数,inputData需为数值型列表。
内容的提问来源于stack exchange,提问作者marital_weeping
相关产品推荐
相关产品推荐

