フィルターのクリア

Regression testing code that takes user input via the input() function

4 ビュー (過去 30 日間)
Chad Gilbert
Chad Gilbert 2013 年 11 月 6 日
編集済み: Andy Campbell 2013 年 11 月 7 日
I have a convenience library/application that sometimes prompts a user for extra input from the command-line. An example might be:
>> connectToRemoteService(1,2,3);
You are now connected to the remote service. Tell it what you need!
MYSERVICE:>
The user might call several commands before returning to the MATLAB prompt.
I am currently exercising the back-end code for this library using the new matlab.unittest capability and am quite happy with it. But I'd like to also stimulate the code using the input() function. Is there a nice way for me to automate this in MATLAB?

採用された回答

Andy Campbell
Andy Campbell 2013 年 11 月 6 日
編集済み: Andy Campbell 2013 年 11 月 7 日
Hi Chad,
I am glad that the framework is working well for you!
Currently in order to use a mock/stub/fake/spy for a function in MATLAB you can create a fake implementation of the function and place it in a location that is normally off the path. Then you can add it to the path in your test in order to get that fake implementation called when the code under test invokes the function.
This might look like:
classdef MyInputTest < matlab.unittest.TestCase
methods(Test)
function tickleInputRelatedCode(testCase)
testCase.injectInputStub('user response');
result = executeCodeUnderTestWhichCallsInput;
testCase.verifyEqual(result, 'user response');
end
end
methods(Access=private)
function injectInputStub(testCase, answer)
import matlab.unittest.fixtures.PathFixture;
% Use the PathFixture to temporarily add the folder to the path
% and restore it when the test method completes
testCase.applyFixture(PathFixture('overloads/input'));
% Register the fake input function to return the desired user answer
input('','', answer);
end
end
end
Then in an 'overloads/input' folder you might have:
function result = input(~, ~, injectedAnswer)
% Overloaded input function for use in testing. Since input only takes two arguments,
% passing a third argument injects the desired answer the user is returning.
persistent ANSWER;
if nargin > 2
ANSWER = injectedAnswer;
else
result = ANSWER;
end
Of course this is one of many ways you can inject your answer. Does this help you get started?
Thanks,
Andy

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTesting Frameworks についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by