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!