Matlab:测试接受用户键盘输入的类

问题描述 投票:0回答:1

我想测试一个从用户那里获取键盘输入的类

GetInput
。 我的测试类如何为
GetInput
提供模拟键盘输入? 这是要测试的类。

classdef GetInput

    properties
        Answer
    end

    methods
        function obj = GetInput
            obj.Answer = input("Your answer? ","s");
        end
    end
end

这是测试课。

classdef testGetInput < matlab.unittest.TestCase

    methods (Test)

        function tInput(testCase)
            g = GetInput();    
            myInput = 'abcdef';
            % I want to provide input automatically at this point   
            verifyEqual(testCase,g.Answer,myInput)
        end
    end
end

这一切都有效,但前提是我在命令窗口提示符下手动输入“abcdef”。 我想要一种自动键盘输入的方法。

matlab
1个回答
0
投票

具体操作方法如下。 有点绕了。 从输入接口类开始:

classdef (Abstract) InputInterface
    methods
        inp = getInput(inputGetter,prompt)
    end
end

创建继承抽象接口的默认输入类KeyboardInput:

classdef KeyboardInput < InputInterface
    methods
        function inp = getInput(~,prompt) % 1st input arg is InputInterface obj
            inp = input(prompt,"s");
        end
    end
end

添加一个使用以下输入类之一的 UserQuery 类:

classdef UserQuery < handle

    properties
        InputSource
        Response
    end

    methods
        function obj = UserQuery(inputSrc)
            arguments
                inputSrc (1,1) InputInterface = KeyboardInput
            end
            obj.InputSource = inputSrc;
        end

        function ask(obj,prompt)
            obj.Response = obj.InputSource.getInput(prompt);
        end
    end
end

现在用模拟测试 UserQuery:

classdef tUserQuery < matlab.mock.TestCase

    properties
        Mock
        Behavior
        Asker
    end

    methods (Test)
        function testInput(tc)
            userSaid = "whatUserSaid";
            when(tc.Behavior.getInput(99), ...
                matlab.mock.actions.AssignOutputs(userSaid))
            tc.Asker.ask(99)            
            tc.verifyTrue(isequal(tc.Asker.Response,userSaid))
        end
    end

    methods (TestClassSetup)
        function setupMock(tc)
            [tc.Mock,tc.Behavior] = tc.createMock(?InputInterface);
            tc.Asker = UserQuery(tc.Mock);
        end
    end

end    

模拟继承自抽象InputInterface,因此UserQuery接受它作为输入参数。 设置模拟行为,以便当使用输入参数 99 调用它时,它输出“whatUserSaid”。

>> q = UserQuery(KeyboardInput);
>> q.ask("Your answer? ")
Your answer? yes
>> q

q = 

  UserQuery with properties:

    InputSource: [1×1 KeyboardInput]
       Response: 'yes'

>> 
© www.soinside.com 2019 - 2024. All rights reserved.