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

조회 수: 21 (최근 30일)
Chris
Chris 2025년 10월 2일 13:47
댓글: dpb 2025년 10월 2일 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
Chris
Chris 2025년 10월 2일 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 2025년 10월 2일 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.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Mocking Framework에 대해 자세히 알아보기

제품


릴리스

R2025a

Community Treasure Hunt

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

Start Hunting!

Translated by