How can I force Matlab to run an enum class constructor?

조회 수: 5 (최근 30일)
Matt
Matt 2020년 2월 28일
댓글: Matt 2020년 2월 28일
I have the following enum class:
classdef MyEnum
properties
prop1
end
enumeration
A( 1, 2 )
B( 3, 4 )
end
methods( Access = public )
function this = MyEnum( x, y )
fprintf( 'Running MyEnum constructor...\n' );
this.prop1 = x + y;
end
end
end
The first time I instantiate an object of type MyEnum after opening Matlab or clearing classes, or when I make a change to MyEnum.m and save it, Matlab runs the constructor once for each enumeration:
>> foo = MyEnum.A;
Running MyEnum constructor...
Running MyEnum constructor...
>> foo = MyEnum.B;
>> clear classes
>> foo = MyEnum.B;
Running MyEnum constructor...
Running MyEnum constructor...
>>
These seem to be the only ways to run the constructor; running "clear MyEnum" and instantiating another object also doesn't run the constructor. I'd like to run it without clearing everything (as "clear classes" does). Is there a way to do this?

답변 (1개)

Matt J
Matt J 2020년 2월 28일
I'd like to run it without clearing everything (as "clear classes" does). Is there a way to do this?
You don't need to clear everything. Clearing both the class and any lingering objects of the class in the workspace would be sufficient. For example,
>> clear classes;
>> obj=myclass.A;
Running myclass constructor...
Running myclass constructor...
>> clear obj; clear myclass;
>> obj=myclass.A;
Running myclass constructor...
Running myclass constructor...
  댓글 수: 1
Matt
Matt 2020년 2월 28일
Excellent! But, and I probably should've mentioned this before but I was hoping a simple explanation would help and I wouldn't need to dive into really hairy details, my issue is when running unit testing code on the class - it's a property of the test case so I can run unit testing on it with ParameterCombination = 'sequential':
classdef MyEnumTest < matlab.unittest.TestCase
properties( TestParameter )
testEnum = arrayfun( @( x ) x, ...
eval( 'enumeration( ''myPackage.MyEnum'' )' ), ...
'UniformOutput', false );
end
methods( Test = true, ParameterCombination = 'sequential' )
function SomeUnitTest( testCase, testEnum )
% Test each enumeration
end
end
end
I'm running the unit testing with the code coverage plugin and the MyEnum constructor isn't getting picked up. I was hoping to add a second simple test and just run the constructor. I could set testEnum to a cell array of strings, but then I'd have to update it if/when the enumeration list changes.

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

카테고리

Help CenterFile Exchange에서 R Language에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by