如何在Matlab测试类中模拟键盘输入测试GetInput类
如何在Matlab测试类中模拟键盘输入给GetInput类
要实现自动化模拟键盘输入,你可以利用Matlab的Mock框架替换内置的input函数,让它返回预设的输入值,无需手动输入。以下是修改后的测试类代码:
classdef testGetInput < matlab.unittest.TestCase methods (Test) function tInput(testCase) % 创建input函数的Mock对象 [mockInput, inputBehavior] = testCase.createMock('AddedFunctions', {'input'}); % 指定当input以指定参数调用时,返回预设的输入字符串 when(inputBehavior.input("Your answer? ","s"), thenReturn('abcdef')); % 测试结束后恢复原input函数,避免影响其他测试 testCase.addTeardown(@clear, 'input'); % 将全局input替换为Mock版本 input = mockInput; % 实例化GetInput,此时会使用Mock的input获取预设值 g = GetInput(); myInput = 'abcdef'; % 验证结果是否符合预期 verifyEqual(testCase, g.Answer, myInput) end end end
关键代码解释:
createMock:创建包含input函数的Mock对象,用于替代真实的input函数。when(...thenReturn(...)):定义Mock的行为——当input被调用时传入参数"Your answer? ","s",就返回预设的'abcdef'。addTeardown:添加测试清理操作,确保测试结束后清除Mock版本的input,恢复Matlab内置的input函数,避免干扰其他测试用例。- 将
mockInput赋值给全局的input变量,这样GetInput类的构造函数调用input时,会使用Mock版本而非等待手动输入。
这样修改后,测试用例会自动使用预设的输入值完成测试,无需手动在命令行输入内容。
内容的提问来源于stack exchange,提问作者Rich006
相关产品推荐
相关产品推荐

