MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

When you create a mock, you also create an associated behavior object. The behavior
object defines the same methods as the mock object and controls mock behavior. Use the
behavior object to define mock actions and qualify interactions. For example, use it to
define values a mocked method returns, or verify that a property was accessed.


At the command prompt, create a mock test case for interactive use. Using the mock in a
test class instead of at the command prompt is presented later in this example.


import matlab.mock.TestCase
testCase = TestCase.forInteractiveUse;


Create Stub to Define Behavior


Create a mock for the data service dependency and examine the methods on it. The data
service mock returns predefined values, replacing the implementation of the service that
provides actual stock prices. Therefore, it exhibits stubbing behavior.


[stubDataService,dataServiceBehavior] = createMock(testCase,?DataService);
methods(stubDataService)


Methods for class matlab.mock.classes.DataServiceMock:


Static methods:


lookupPrice


In the DataService class, the lookupPrice method is abstract and static. The mocking
framework implements this method as concrete and static.


Define behavior for the data service mock. For ticker symbol "FOO", it returns the price
yesterday as $123 and anything before yesterday is $234. Therefore, according to the
trader function, the broker always buys stock "FOO". For the ticker symbol "BAR", it
returns the price yesterday as $765 and anything before yesterday is $543. Therefore, the
broker never buys stock "BAR".


import matlab.unittest.constraints.IsLessThan
yesterday = datetime('yesterday');


testCase.assignOutputsWhen(dataServiceBehavior.lookupPrice(...
"FOO",yesterday),123);


Create Mock Object
Free download pdf