MATLAB自动化测试:GINPUTZOOM在脚本中的调用技巧
·
MATLAB自动化测试:ginputzoom在脚本中的调用技巧
ginputzoom是MATLAB中用于在图形窗口交互式获取坐标点的自定义函数(需自行实现或获取第三方版本)。在自动化测试中调用时需解决交互依赖问题,以下是关键技巧:
1. 模拟输入法(推荐)
修改ginputzoom源码,使其在测试模式下从预设队列读取坐标:
function [x,y] = ginputzoom(varargin)
if isappdata(gcf, 'TestMode') % 检测测试标志
ptQueue = getappdata(gcf, 'ptQueue');
x = ptQueue(1,1);
y = ptQueue(1,2);
ptQueue(1,:) = []; % 移除已用点
setappdata(gcf, 'ptQueue', ptQueue);
else
% 原交互式代码(如基于ginput和zoom的实现)
end
end
测试脚本示例:
% 创建测试图形
figure; plot(rand(10,1));
setappdata(gcf, 'TestMode', true); % 激活测试模式
setappdata(gcf, 'ptQueue', [0.3,0.5; 0.7,0.8]); % 预设坐标队列
% 调用被测函数
[x1,y1] = ginputzoom();
[x2,y2] = ginputzoom();
assert(abs(x1-0.3)<0.01 && abs(y2-0.8)<0.01)
2. 回调注入法
通过图形对象回调模拟点击事件:
% 设置自动化点击
function simulateClick(fig, x, y)
set(fig, 'CurrentPoint', [x,y]); % 设置当前点
h = findobj(fig, 'Type', 'axes');
feval(get(h, 'ButtonDownFcn'), h, []) % 触发回调
end
% 测试脚本
fig = figure;
plot(sin(0:0.1:2*pi));
simulateClick(fig, 3.0, 0.5); % 模拟点击(3.0,0.5)
3. 外部控制法(跨进程)
使用操作系统级自动化工具:
- Windows:通过
.NET调用System.Windows.Forms.Cursor.Position - Mac/Linux:使用
xdotool(需安装)
% Windows示例(需.NET支持)
mouse_event = actxserver('wscript.shell');
mouse_event.SendKeys('{CLICK 500,300}'); % 屏幕坐标
最佳实践建议
-
隔离依赖
% 封装被测函数 function output = test_wrapper() setappdata(gcf, 'ptQueue', [..]); % 预设输入 output = ginputzoom(); end -
坐标转换 使用
gca坐标转换保证精度: $$ \text{屏幕坐标} \rightarrow \text{数据坐标} $$ax = gca; testPoint = [0.5, 0.7]; pixelPos = ax.DataToPixel.transform(testPoint); % 需MATLAB R2020b+ -
异常处理
try [x,y] = ginputzoom(); catch ME if contains(ME.message, 'No test points') logError("测试点队列耗尽"); end end
验证方法
graph TD
A[启动测试] --> B[加载预设坐标]
B --> C{调用ginputzoom}
C --> D[捕获输出]
D --> E[比较预期坐标]
E -->|误差<阈值| F[标记成功]
E -->|误差≥阈值| G[生成差异报告]
注意:实际坐标比较需考虑浮点精度:
tolerance = 1e-5; assert(abs(x_actual - x_expected) < tolerance)
更多推荐



所有评论(0)