polyspace.project.Mock Class
Namespace: polyspace.project
Description
Create a mock function to override the definition of a C/C++ function in the source code added to a Polyspace® Platform project.
Creation
Syntax
Description
mock = proj.Mocks.create( creates a mock for function functionToMock)functionToMock in a polyspace.project.Project object proj. The mock name is the name of the original function followed by _mock.
mock = proj.Mocks.create( creates a mock for function functionToMock, PropertyName=Value)functionToMock and assigns one or more of its properties during creation.
mock = proj.Mocks.createFrom(
creates a new mock by duplicating an existing mock.existingMock, newMockName)
Input Arguments
Function to mock, specified as a polyspace.project.Function object.
Get the polyspace.project.Function object for a function by parsing the code associated with a polyspace.project.Project object proj and using the getFunctionBySignature method for the resulting polyspace.project.CodeInfo object.
For example, use this code to get the polyspace.project.Function object for the function with signature void init(int) in the project proj:
codeInfo = polyspace.project.parseCode(proj)
functionToMock = codeInfo.getFunctionBySignature("void init(int)")For more information, see polyspace.project.CodeInfo.
Existing mock, specified as a polyspace.project.Mock object.
The existing mock object can be from any project.
Name of new mock specified as a string. This name is assigned to the Name property of the newly created mock.
Properties
Name of mock, specified as a string. This name is assigned to the Name property of the polyspace.project.Mock object and appears as the mock name when you open the associated project in the Polyspace Platform user interface.
Names of arguments to the mock, specified as an array of strings. Each mock argument has the same type as the type of the corresponding function argument.
If you do not set this property explicitly, the mock argument names are the same as the function argument names. For unnamed function arguments, the mock argument names are automatically generated.
Example:
["arg0", "arg1", "arg2"]
Code that goes outside the mock body, such as global variable declarations or type declarations, specified as a string. This code allows the mock definition to be compiled in isolation. In most cases, you add #include-s to header files containing the required declarations.
Example:
'#include "types.h"'
Code that goes inside the mock body (excluding the mock signature), specified as a string.
Example:
"int aGlobal1 = num;"
Variable declarations to export from the mock, specified as a string.
Example:
"extern int statusVar;"
List of variables whose declarations are exported from a mock using the ExportedDeclarations property. A mock variable can looked up in the list using its name and accessed from the inputs or assessments of a test.
For an example usage of this property, see Change Mock Implementation Using Test Inputs.
Examples
Create a mock for a function and apply the mock in a test. For equivalent steps in the Polyspace Platform user interface, see Override Callee Definitions When Testing Functions in Polyspace Platform User Interface.
Inspect the file
inits.cin the folder. Here,polyspaceroot\polyspace\examples\doc_pstest\test_with_mocked_callee\srcis the Polyspace installation folder, for instance,polyspacerootC:\Program Files\Polyspace\R2026a.The file contains a function
set()that calls another functioninit()to write to global variables.In the following two scripts, you write a test for the function#include "decls.h" extern int32_t aGlobal1; extern int32_t aGlobal2; void init(int32_t num) { aGlobal1 = num; aGlobal2 = num; } void set(int32_t num) { init(num); }set()by mocking the functioninit()and see the effect of applying the mock.Create a test for the function
set()leaving the default implementation of the functioninit():When you run the script, you see failing test results because the functionimport polyspace.project, polyspace.test import os # Add source file "inits.c" to a project and parse source code proj = polyspace.project.Project("myProject") proj.Code.Files.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "test_with_mocked_callee", "src", "inits.c" ) ) proj.IncludePaths.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "test_with_mocked_callee", "src" ) ) codeInfo = polyspace.project.parseCode(proj) # Create test for "set()" function suite = proj.TestSuites.create("globalUpdateSuite") test = suite.TestCases.create("globalUpdateTest") funcToTest = codeInfo.getFunctionBySignature("void set(int32_t)") testStep = test.TestSteps.createTabular("setGlobal", funcToTest) testStep.Inputs["num"].Value = "1" testStep.Assessments["aGlobal1"].Value = "0" testStep.Assessments["aGlobal2"].Value = "0" # Run test res = polyspace.test.run(proj) print(res.SuitesPassed)init()initializes the global variables to 1, but the assessments compare the value against 0.Modify the previous test to apply a mock for the
init()function:When you run the script, the test passes now because the mock body overrides the implementation of the# Import required modules import polyspace.project import polyspace.test import os # Add source file "inits.c" to a project and parse source code projWithMocks = polyspace.project.Project("myProjectWithMocks") projWithMocks.Code.Files.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "test_with_mocked_callee", "src", "inits.c" ) ) projWithMocks.IncludePaths.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "test_with_mocked_callee", "src" ) ) codeInfo = polyspace.project.parseCode(projWithMocks) # Create mock for "init()" function projectMocks = projWithMocks.Mocks funcToMock = codeInfo.getFunctionBySignature("void init(int32_t)") mockInit = projectMocks.create(funcToMock, Name="init_mock") mockInit.Header = """#include <stdint.h> extern int32_t aGlobal1; extern int32_t aGlobal2;""" mockInit.Body = """ aGlobal1 = 0; aGlobal2 = 0;""" # Create test for "set()" function suite = projWithMocks.TestSuites.create("globalUpdateSuite") test = suite.TestCases.create("globalUpdateTest") funcToTest = codeInfo.getFunctionBySignature("void set(int32_t)") testStep = test.TestSteps.createTabular("setGlobal", funcToTest) testStep.Inputs["num"].Value = "1" testStep.Assessments["aGlobal1"].Value = "0" testStep.Assessments["aGlobal2"].Value = "0" # Apply mock on test testStep.ActiveMocks.add(mockInit) # Run test res = polyspace.test.run(projWithMocks) print(res.SuitesPassed)init()function.
Create a single mock that can have different implementations in different tests and choose the mock implementation using test inputs. For equivalent steps in the Polyspace Platform user interface, see Change Mock or Stub Implementation Based on Test.
Inspect the following files in the folder
.polyspaceroot\polyspace\examples\doc_pstest\mock_variables\srcdecls.hcontains the definitions of typesreadStatusandState:#ifndef DECLS_H #define DECLS_H enum readStatus { R_SUCCESS, R_FAILURE }; struct State { int indicator; int updateCount; }; enum readStatus readData(void); void updateState(struct State* stateVariable); #endifexample.ccontains the definitions of functionsreadData()andupdateStatus():In the following two scripts, you write a test for the function#include "decls.h" enum readStatus readData(void) { //readData() implementation } void updateState(struct State* stateVariable) { enum readStatus status = readData(); if (status == R_SUCCESS) { stateVariable->indicator = 1; stateVariable->updateCount++; } }updateState()by mocking the functionreadData()and see the effect of applying the mock.
Create a test for the function
updateState()as follows:When you run the script, you see failing test results because the function# Import the required modules import polyspace.project import polyspace.test import os # Add source file "example.c" and include paths # To a project and parse the source code proj = polyspace.project.Project("myProjectWithMocks") proj.Code.Files.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "mock_variables", "src", "example.c" ) ) proj.IncludePaths.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "test_with_mocked_callee", "src" ) ) codeInfo = polyspace.project.parseCode(proj) # Create test suite = proj.TestSuites.create("updateSuite") test = suite.TestCases.create("updateTest") # Create test step to invoke function "updateState()" funcToTest = codeInfo.getFunctionBySignature("void updateState(struct State*)") testStep = test.TestSteps.createTabular("updateTest", funcToTest) # Create pointer targets to variables of type "struct State" structType = codeInfo.getType("struct State[1]") inputTarget = test.TestData.create("inputState", structType) # All fields implicitly set to 0 outputTarget = test.TestData.create("outputState", structType) test.TestData["outputState"][0]["indicator"].Value = "1" test.TestData["outputState"][0]["updateCount"].Value = "1" # Set test inputs and assessments testStep.Inputs["stateVariable"].Value = inputTarget testStep.Assessments["stateVariable"].Value = outputTarget # Run test res = polyspace.test.run(proj) print(res.SuitesPassed)updateState()bypasses theifstatement and does not modify its input.Modify the previous test to apply a mock on the
readData()function:When you run the script, the test now passes because the mock body overrides the implementation of the# Import the required modules import polyspace.project import polyspace.test import os # Add source file "example.c" and include paths # To a project and parse the source code projWithMocks = polyspace.project.Project("myProject") projWithMocks.Code.Files.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "mock_variables", "src", "example.c" ) ) projWithMocks.IncludePaths.add( os.path.join( polyspace.__install_path__, "polyspace", "examples", "doc_pstest", "mock_variables", "src" ) ) codeInfo = polyspace.project.parseCode(projWithMocks) # Create mock for "readData()" function projectMocks = projWithMocks.Mocks funcToMock = codeInfo.getFunctionBySignature("enum readStatus readData(void)") mockReadData = projectMocks.create(funcToMock, Name="readData_mock") mockReadData.Header = '''#include "decls.h" enum readStatus statusMockVar;''' mockReadData.ExportedDeclarations = '''#include "decls.h" extern enum readStatus statusMockVar;''' mockReadData.Body = "return statusMockVar;" # Create test suite = projWithMocks.TestSuites.create("updateSuite") test = suite.TestCases.create("updateTest") # Create test step to invoke function "updateState()" funcToTest = codeInfo.getFunctionBySignature("void updateState(struct State*)") testStep = test.TestSteps.createTabular("updateTest", funcToTest) # Create pointer targets to variables of type "struct State" structType = codeInfo.getType("struct State[1]") inputTarget = test.TestData.create("inputState", structType) # All fields implicitly set to 0 outputTarget = test.TestData.create("outputState", structType) test.TestData["outputState"][0]["indicator"].Value = "1" test.TestData["outputState"][0]["updateCount"].Value = "1" # Set test inputs and assessments testStep.Inputs["stateVariable"].Value = inputTarget testStep.Assessments["stateVariable"].Value = outputTarget # Run test res = polyspace.test.run(projWithMocks) print(res.SuitesPassed) # Apply mock on test testStep.ActiveMocks.add(mockReadData) # Create test input from the exported mock variable "statusMockVar" # Set input value testStep.Inputs.create(mockReadData.ExportedVariables["statusMockVar"]) testStep.Inputs["statusMockVar"].Value = "R_SUCCESS" # Run the test res = polyspace.test.run(projWithMocks) print(res.SuitesPassed)readData()function. The exported mock variable valueR_SUCCESScauses the mock to have this implementation:This implementation causes the callerenum readStatus readData(void) { return R_SUCCESS; }updateState()to enter the body of theifstatement and modify its input.
Limitations
Polyspace Test™ does not support the creation of mocks for:
Variadic functions
Template functions or methods
Operators, constructors, or destructors
Functions defined in header files
Methods for classes defined in source files
Inline methods
Functions with a parameter type that is defined in a source file
Version History
Introduced in R2026a
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Seleziona un sito web
Seleziona un sito web per visualizzare contenuto tradotto dove disponibile e vedere eventi e offerte locali. In base alla tua area geografica, ti consigliamo di selezionare: .
Puoi anche selezionare un sito web dal seguente elenco:
Come ottenere le migliori prestazioni del sito
Per ottenere le migliori prestazioni del sito, seleziona il sito cinese (in cinese o in inglese). I siti MathWorks per gli altri paesi non sono ottimizzati per essere visitati dalla tua area geografica.
Americhe
- América Latina (Español)
- Canada (English)
- United States (English)
Europa
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)