Regression testing code that takes user input via the input() function
5 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!