MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Using a mock object, you can define behavior (a process known as stubbing). For
example, you can specify that an object produces predefined responses to queries. You
can also intercept and remember messages sent from the component under test to the
mock object (a process known as spying). For example, you can verify that a particular
method was called or a property was set.


The typical workflow to test a component in isolation is as follows:


(^1) Create mocks for the depended-on components.
(^2) Define behaviors of the mocks. For example, define the outputs that a mocked
method or property returns when it is called with a particular set of inputs.
(^3) Test the component of interest.
(^4) Qualify interactions between the component of interest and the mocked components.
For example, verify that a mocked method was called with particular inputs, or that a
property was set.
Depended on Components
In this example, the component under test is a simple day-trading algorithm. It is the part
of the system you want to test independent of other components. The day-trading
algorithm has two dependencies: a data service to retrieve the stock price data and a
broker to purchase the stock.
In a file DataService.m in your current working folder, create an abstract class that
includes a lookupPrice method.
classdef DataService
methods (Abstract,Static)
price = lookupPrice(ticker,date)
end
end
In production code, there could be several concrete implementations of the DataService
class, such as a BloombergDataService class. This class uses the Datafeed Toolbox™.
However, since we create a mock of the DataService class, you do not need to have the
toolbox installed to run the tests for the trading algorithm.
classdef BloombergDataService < DataService
methods (Static)
Create Mock Object

Free download pdf