What are some ways to mock 'system' for unit testing?
이전 댓글 표시
I need to mock returns from calls to 'system' for the purpose of unit testing. I tried overloading the built-in by creating a 'system.m' function that lives in the same folder as my unit tests but the testing framework called foul on that approach and skips the tests that use it:
Warning: Function system has the same name as a MATLAB built-in. We suggest you rename the function to avoid a potential name conflict.
> In matlab.unittest.TestSuite>temporarilyChangeFolderIfNeeded (line 881)
In matlab.unittest.TestSuite.fromFileCore_ (line 694)
In matlab.unittest.TestSuite.fromFile (line 178)
In matlab.unittest.internal.testbrowser/AlertHandler/callFunctionAndHandleAlerts
In matlab.unittest.internal.testbrowser/SuiteFromFileForTestImport/execute
In matlab.unittest.internal.testbrowser/TestModelService/loadTestFile
In matlab.unittest.internal.testbrowser/TestModelService/loadTestFiles
In matlab.unittest.internal.testbrowser/TestBrowserController/importTestFiles
In matlab.unittest.internal.testbrowser.TestBrowserActionsService.importFilesInJavaDesktop
One approach is to create a wrapper method for 'system' in the class under test, then create a wrapper class that inherits 'myClass' that is used for testing:
class I want to test
classdef myClass
methods
function [status,cmdout]=systemWrapper(varargin)
[status,cmdout]=system(varargin)
% varargout parsing... blah blah
end
end
end
mock class called by tests to overload 'systemWrapper'
classdef myClassMocked < myClass
methods
function [status,cmdout]=systemWrapper(varargin)
[status,cmdout]=systemMock(varargin)
% varargout parsing... blah blah
end
end
end
I think that should work, but it just smells a bit convoluted and seems like there should be a cleaner way to mock 'system' directly.
댓글 수: 3
dpb
2025년 10월 2일
Never used the testing framework, but it's a warning, not an error, so I would think the first would still function as wanted.
Since in this case you delibertely alias system you could turn off the warning before by using with
[id,msg]=lastwarn;
at command line to get the precise warning id and then
warning('off',id)
before initiating the test. Reinstate the warning state afterwards, of course.
Chris
2025년 10월 2일
dpb
2025년 10월 2일
Well, that sucks, doesn't it? It was just a hypothesis, too bad it wasn't the right one.
If somebody doesn't come along with Framework experience and a better idea, I'd recomend to submit this to Mathworks as an official support request at <Product Support Page> for better approach and/or enhancement request to have a way to force the test despite the specific warning; it seems a reasonable use case for why one would really, indeed, want to alias the builtin.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Mock Dependencies in Tests에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!