MATLAB: Testing private functions in classes

object-oriented progammingoopunit tests

I'm wondering what the best way is to write unit tests for private functions and properties in classes. Say for example, I have a class that represents a ball launched as a projectile:
class ball
%


properties (Access = private)
initialSpeed = 25; %m/s
acceleration = -10; %m/s^2
end
%
methods
function distTravelled = getDistanceTravelled(obj, timeElapsed)
% Estimate total distance traveled by the ball
% (I know this is a bad approximation)
currSpeed = obj.getCurrSpeed(timeElapsed);
distTravelled = 0.5 * (obj.initialSpeed + currSpeed) * timeElapsed;
end
end
%
methods (Access = private)
function currSpeed = getCurrSpeed(obj, timeElapsed)
%Calculate current speed of ball
currSpeed = obj.initialSpeed + obj.acceleration * timeElapsed;
end
end
end
How should I write a test to check that the values for acceleration or that the value returned by the method getCurrSpeed is accurate? Should I just allow access to the testing functions?

Best Answer

First goggle "test private method" and read about why you should not do it (and a few ways to do it).
One way (for handle classes only) is to include the test in the class itself.
>> mc = MyClass
mc =
MyClass with no properties.
>> mc.test_private
Private mysort is running
>>
where
classdef MyClass < matlab.unittest.TestCase
%
methods ( Test )
function test_private( this )
this.mysort
end
end
methods ( Access = private )
function mysort( this )
fprintf( 'Private mysort is running\n' )
end
end
end
A better workaround based on localfunctions (added 19 hours later)
>> mc = MyClass;
>> fh = mc.get_local_function_handle;
>> fh = fh{1}
fh =
@the_tricky_algorithm_
>> fh( mc )
ans =
144
>>
where in one mfile
classdef MyClass
properties
val = 12;
end
methods
function fh = get_local_function_handle( ~ )
fh = localfunctions();
end
end
methods ( Access = private )
function my_private_method( this )
fprintf( 'Private mysort is running\n' )
the_tricky_algorithm_( this )
end
end
end
function out = the_tricky_algorithm_( this )
out = this.val .* this.val;
end