What are some ways to mock 'system' for unit testing?

16 views (last 30 days)
Chris
Chris on 2 Oct 2025 at 13:47
Commented: dpb on 2 Oct 2025 at 15:53
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 Comments
Chris
Chris on 2 Oct 2025 at 15:36
Thanks, @dpb, but the framework actually skips the test; it uses warnings rather than exceptions so the rest of the test suite can finish.
dpb
dpb on 2 Oct 2025 at 15:53
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.

Sign in to comment.

Answers (0)

Products


Release

R2025a

Community Treasure Hunt

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

Start Hunting!