TestHelpers
in package
The main API functions for Test Helpers.
Use only static calls like TestHelpers::method()
.
Table of Contents
Constants
- REQUEST_STUB_DEFAULT_URI = 'http://drupal-unit-test.local/'
- An uri with a placeholder domain, to use in requests by default.
Methods
- addFieldPlugin() : void
- Adds a field plugin from class to the typed data manager.
- addIteratorToMock() : MockObject
- Sets an array as the iterator on a mocked object.
- assertException() : mixed
- Asserts that a function throws a specific exception.
- callEventSubscriber() : void
- Calls an event subscriber with checking the definition in services.
- callPrivateMethod() : mixed
- Calls a private or protected method from a class using reflection.
- createClass() : object
- Creates a class via calling function create() with container.
- createEntity() : EntityStubInterface|EntityInterface|MockObject
- Creates a stub entity for an entity type from a given class.
- createFieldStub() : FieldItemListInterface
- Creates a field instance stub.
- createMock() : MockObject
- Returns a mock object for the specified class.
- createPartialMock() : MockObject
- Returns a partial mock object for the specified class.
- createPartialMockWithConstructor() : MockObject
- Creates a partial mock for the class and call constructor with arguments.
- createPartialMockWithCustomMethods() : MockObject
- Creates a partial mock with ability to add custom methods.
- findQueryCondition() : array<string|int, mixed>|null
- Searches query conditions by a field name or sub-conditions.
- getClassFile() : bool|string
- Gets a path to file for the class.
- getClassResolverStub() : mixed
- Returns a stub class resolver.
- getContainer() : ContainerInterface
- Gets a Drupal services container, or creates a new one.
- getContainerWithCacheTagsInvalidator() : mixed
- Sets up a container with a cache tags invalidator.
- getDrupalRoot() : string
- Finds a Drupal root directory.
- getEntityStorage() : EntityStorageInterface
- Gets or initializes an Entity Storage for a given Entity Type class name.
- getMockedMethod() : InvocationMocker
- Gets a mocked method from the Mock object to replace return value.
- getModuleFilePath() : string
- Gets the absolute path to a file in the called module by a relative path.
- getModuleName() : string|null
- Gets a module name from a namespace of a module class.
- getModuleRoot() : string|null
- Gets a root module folder from a module file full path.
- getPluginDefinition() : mixed
- Parses the annotation for a class and gets the definition.
- getPrivateMethod() : ReflectionMethod
- Gets a private or protected method from a class using reflection.
- getPrivateProperty() : mixed
- Gets a private or protected property from a class using reflection.
- getRandomGenerator() : mixed
- Gets the random generator for the utility methods.
- getServiceInfoFromClass() : array<string|int, mixed>|null
- Gets information about service from YAML file.
- getStringTranslationStub() : mixed
- Returns a stub translation manager that just returns the passed string.
- initEntityTypeManagerStubs() : void
- Initializes the main services to work with entities stubs.
- initService() : object
- Initializes a service from the service name or class.
- initServiceFromYaml() : object
- Initializes a service from YAML file with passing services as arguments.
- isNestedArraySubsetOf() : bool
- Performs a check if the actial array is a subset of expected.
- loadParametersFromYamlFile() : void
- Load params from YAML file to the current service container.
- matchConditions() : bool
- Performs matching of passed conditions with the query.
- matchEntityCondition() : bool
- Matches a EntityQuery conditon to entity.
- mockPhpFunction() : MockedFunctionCalls
- Sets a mock for a PHP build-in function for the namespace of a class.
- queryIsSubsetOf() : bool
- Performs matching of passed conditions with the query.
- saveEntity() : EntityStubInterface|EntityInterface|MockObject
- Creates a stub entity for an entity type from a given class and saves it.
- service() : object
- Gets the service stub or mock, or initiates a new one if missing.
- setMockedClassMethod() : void
- Sets a closure function to a class method.
- setPrivateProperty() : void
- Sets a private or protected property value in a class using reflection.
- setServices() : void
- Initializes list of services and adds them to the container.
- unmockAllPhpFunctions() : mixed
- Unmocks all functions, that was mocked by mockPhpFunction().
- unmockPhpFunction() : mixed
- Unmocks the previously mocked PHP build-in function in a namespace.
Constants
REQUEST_STUB_DEFAULT_URI
An uri with a placeholder domain, to use in requests by default.
public
string
REQUEST_STUB_DEFAULT_URI
= 'http://drupal-unit-test.local/'
It is used to produce absolute links when no request is pushed manually to the 'request_stack' service.
You can override this default behavior in your unit test via:
TestHelpers::service('request_stack')->push(Request::create('https://example.com/some-path');
Example of how to check the url with the default request stub:
$this->assertEquals(
TestHelpers::REQUEST_STUB_DEFAULT_URI,
$service->getCurrentRequest()->getUri()
);
Methods
addFieldPlugin()
Adds a field plugin from class to the typed data manager.
public
static addFieldPlugin(string $class) : void
Parameters
- $class : string
-
The field plugin class.
addIteratorToMock()
Sets an array as the iterator on a mocked object.
public
static addIteratorToMock(array<string|int, mixed> $array, MockObject $mock) : MockObject
Parameters
- $array : array<string|int, mixed>
-
The array with data.
- $mock : MockObject
-
The mocked object.
Return values
MockObject —The mocked object.
assertException()
Asserts that a function throws a specific exception.
public
static assertException(callable $function[, string $exceptionClass = NULL ][, string $message = NULL ]) : mixed
Parameters
- $function : callable
-
A function to execute.
- $exceptionClass : string = NULL
-
(optional) An exception class to assert, \Exception by default.
- $message : string = NULL
-
(optional) A message text to throw on missing exception.
Tags
callEventSubscriber()
Calls an event subscriber with checking the definition in services.
public
static callEventSubscriber(string|array<string|int, mixed>|object $service, string $eventName, object &$event) : void
Checks that the event subscriber has a definition in services.yml file and the 'event_subscriber' tag in it, before calling.
Parameters
- $service : string|array<string|int, mixed>|object
-
A service class as a string, or an array with the service info, where:
- the first element is a path to the service YAML file,
- the second element - the service name.
- $eventName : string
-
The Event name.
- $event : object
-
The Event object.
callPrivateMethod()
Calls a private or protected method from a class using reflection.
public
static callPrivateMethod(object|string $class, string $methodName[, array<string|int, mixed> $arguments = [] ]) : mixed
Parameters
- $class : object|string
-
The class instance or the name of the class.
- $methodName : string
-
The name of the method to get.
- $arguments : array<string|int, mixed> = []
-
The list of aruments for the calling method.
Return values
mixed —The return value of the executed function.
createClass()
Creates a class via calling function create() with container.
public
static createClass(string|object $class[, array<string|int, mixed> $createArguments = NULL ][, array<string|int, mixed> $services = NULL ]) : object
Parameters
- $class : string|object
-
The class to test, can be a string with path or initialized class.
- $createArguments : array<string|int, mixed> = NULL
-
The list of arguments for passing to the function create(), excluding the container as the first argument, because it is mandatory, so it is passed automatically.
- $services : array<string|int, mixed> = NULL
-
The array of services to add to the container. Format is same as in function setServices().
Return values
object —The initialized class instance.
createEntity()
Creates a stub entity for an entity type from a given class.
public
static createEntity(string $entityTypeNameOrClass[, array<string|int, mixed> $values = NULL ][, array<string|int, mixed> $translations = NULL ][, array<string|int, mixed> $options = NULL ]) : EntityStubInterface|EntityInterface|MockObject
Parameters
- $entityTypeNameOrClass : string
-
A full path to an entity type class, or an entity type id for Drupal Core entities like
node
,taxonomy_term
, etc. - $values : array<string|int, mixed> = NULL
-
A list of values to set in the created entity.
- $translations : array<string|int, mixed> = NULL
-
A list of translations to add to the created entity.
- $options : array<string|int, mixed> = NULL
-
A list of options to entity stub creation:
- mockMethods: list of methods to make mockable.
- addMethods: list of additional methods.
- skipPrePostSave: a flag to use direct save on the storage without calling preSave and postSave functions. Can be useful if that functions have dependencies which hard to mock. Applies only on the first initialization of this node type.
- skipEntityConstructor: a flag to skip calling the entity constructor.
- fields: a list of custom field options by field name.
Applies only on the first initialization of this field.
Supportable formats:
- A string, indicating field type, like 'integer', 'string', 'entity_reference', only core field types are supported.
- An array with field configuration: type, settings, etc, like this: [ 'type' => 'entity_reference', 'settings' => ['target_type' => 'node'] 'translatable' => TRUE, 'required' => FALSE, 'cardinality' => 3, ].
- A field definition object, that will be applied to the field.
Return values
EntityStubInterface|EntityInterface|MockObject —The stub object for the entity.
createFieldStub()
Creates a field instance stub.
public
static createFieldStub([array<string|int, mixed>|string|null $values = NULL ][, string|FieldDefinitionInterface|null $typeOrDefinition = NULL ][, string|null $name = NULL ][, TypedDataInterface|null $parent = NULL ][, bool|null $isBaseField = NULL ][, array<string|int, mixed>|null $mockMethods = NULL ]) : FieldItemListInterface
Parameters
- $values : array<string|int, mixed>|string|null = NULL
-
The field values.
- $typeOrDefinition : string|FieldDefinitionInterface|null = NULL
-
A field type like 'string', 'integer', 'boolean'. Or a path to a field class like Drupal\Core\Field\Plugin\Field\FieldType\IntegerItem. Or a ready definition object to use. If null - will be created a stub with fallback ItemStubItem definition.
- $name : string|null = NULL
-
The field name.
- $parent : TypedDataInterface|null = NULL
-
Parent item for attaching to the field.
- $isBaseField : bool|null = NULL
-
A flag to create a base field instance.
- $mockMethods : array<string|int, mixed>|null = NULL
-
A list of method to mock when creating the instance.
Return values
FieldItemListInterface —A field item list with items as stubs.
createMock()
Returns a mock object for the specified class.
public
static createMock(string $originalClassName) : MockObject
Parameters
- $originalClassName : string
Tags
Return values
MockObjectcreatePartialMock()
Returns a partial mock object for the specified class.
public
static createPartialMock(string $originalClassName, array<string|int, mixed> $methods) : MockObject
Parameters
- $originalClassName : string
- $methods : array<string|int, mixed>
Tags
Return values
MockObjectcreatePartialMockWithConstructor()
Creates a partial mock for the class and call constructor with arguments.
public
static createPartialMockWithConstructor(string $originalClassName, array<string|int, mixed> $methods[, array<string|int, mixed> $constructorArgs = NULL ][, array<string|int, mixed> $addMethods = NULL ]) : MockObject
Parameters
- $originalClassName : string
- $methods : array<string|int, mixed>
- $constructorArgs : array<string|int, mixed> = NULL
- $addMethods : array<string|int, mixed> = NULL
Return values
MockObjectcreatePartialMockWithCustomMethods()
Creates a partial mock with ability to add custom methods.
public
static createPartialMockWithCustomMethods(string $originalClassName, array<string|int, mixed> $methods[, array<string|int, mixed> $addMethods = NULL ]) : MockObject
Parameters
- $originalClassName : string
- $methods : array<string|int, mixed>
- $addMethods : array<string|int, mixed> = NULL
Return values
MockObjectfindQueryCondition()
Searches query conditions by a field name or sub-conditions.
public
static findQueryCondition(object $query, string|array<string|int, mixed> $requiredCondition[, bool $returnAllMatches = FALSE ]) : array<string|int, mixed>|null
Parameters
- $query : object
-
The query object.
- $requiredCondition : string|array<string|int, mixed>
-
The string with the field name to search. Or an array with sub-conditions like
['field' => 'nid', 'operator' => '<>']
. - $returnAllMatches : bool = FALSE
-
A flag to return all matches as a list, not only the first match.
Return values
array<string|int, mixed>|null —The first matched condition, or NULL if no matcheds.
getClassFile()
Gets a path to file for the class.
public
static getClassFile(mixed $class) : bool|string
Parameters
- $class : mixed
-
Class name or path.
Return values
bool|string —The path to the file.
getClassResolverStub()
Returns a stub class resolver.
public
static getClassResolverStub() : mixed
Tags
getContainer()
Gets a Drupal services container, or creates a new one.
public
static getContainer([bool $forceCreate = FALSE ]) : ContainerInterface
Parameters
- $forceCreate : bool = FALSE
-
Force create a new container, even if already exists.
Return values
ContainerInterface —The initialized container.
getContainerWithCacheTagsInvalidator()
Sets up a container with a cache tags invalidator.
public
static getContainerWithCacheTagsInvalidator(CacheTagsInvalidatorInterface $cache_tags_validator) : mixed
Parameters
- $cache_tags_validator : CacheTagsInvalidatorInterface
Tags
getDrupalRoot()
Finds a Drupal root directory.
public
static getDrupalRoot() : string
Return values
string —A path to the Drupal root directory.
getEntityStorage()
Gets or initializes an Entity Storage for a given Entity Type class name.
public
static getEntityStorage(string $entityTypeNameOrClass[, EntityStorageInterface $storageInstance = NULL ][, bool|null $forceOverride = NULL ][, array<string|int, mixed> $storageOptions = NULL ]) : EntityStorageInterface
Parameters
- $entityTypeNameOrClass : string
-
The entity class.
- $storageInstance : EntityStorageInterface = NULL
-
An already initialized instance of a storage, NULL to create a new one.
- $forceOverride : bool|null = NULL
-
Forces creation of the new clear storage, if exists.
- $storageOptions : array<string|int, mixed> = NULL
-
A list of options to pass to the storage initialization. Acts only once if the storage is not initialized yet.
- skipPrePostSave: a flag to use direct save on the storage without calling preSave and postSave functions. Can be useful if that functions have dependencies which hard to mock.
- constructorArguments: additional arguments to the constructor.
- mockMethods: a list of storage methods to mock.
- addMethods: a list of storage methods to add.
Return values
EntityStorageInterface —The initialized stub of Entity Storage.
getMockedMethod()
Gets a mocked method from the Mock object to replace return value.
public
static getMockedMethod(MockObject $mock, string $method) : InvocationMocker
This allows to replace the return value of the already defined method via
$mockedMethod->willReturn('New Value')
.
It's not possible with PHPUnit API, but here is a feature request about it: https://github.com/sebastianbergmann/phpunit/issues/5070 - please vote!
Parameters
- $mock : MockObject
-
A mocked object.
- $method : string
-
A method to get.
Return values
InvocationMocker —An InvocationMocker object with the method.
getModuleFilePath()
Gets the absolute path to a file in the called module by a relative path.
public
static getModuleFilePath(string $relativePath[, int|null $parentCallsLevel = NULL ]) : string
Usually used for woring with module's YAML files, like
config/install/my_module.settings.yml
or my_module.links.menu.yml
.
The module root is detected by the location of the file, from which this function is called. Use $parentCallsLevel more than zero, if you call this function from an intermediate class.
Parameters
- $relativePath : string
-
A realative path to a file, from the module root directory.
- $parentCallsLevel : int|null = NULL
-
An optional level to skip some parent calls, if you need to detect the module from a parent function, not from which you call this function.
Return values
string —A full path to the module file.
getModuleName()
Gets a module name from a namespace of a module class.
public
static getModuleName([string|int|null $namespaceOrLevel = NULL ]) : string|null
Parameters
- $namespaceOrLevel : string|int|null = NULL
-
The module class namespace. If NULL - gets the namespace from a called function. If numeric - jumps upper the passed number of levels.
Return values
string|null —The module name, or NULL if can't find.
getModuleRoot()
Gets a root module folder from a module file full path.
public
static getModuleRoot([string|int|null $pathOrClassOrLevel = NULL ][, string|null $moduleName = NULL ]) : string|null
Parameters
- $pathOrClassOrLevel : string|int|null = NULL
-
A full path to a file or a class. If empty - gets the path of the function caller file.
- $moduleName : string|null = NULL
-
The name of the module, if empty - gets the caller module name.
Return values
string|null —The full path to the module root.
getPluginDefinition()
Parses the annotation for a class and gets the definition.
public
static getPluginDefinition(string $class[, string $plugin = 'TypedData' ][, string $annotationName = NULL ]) : mixed
Parameters
- $class : string
-
A class name to get definition.
- $plugin : string = 'TypedData'
-
A plugin id.
- $annotationName : string = NULL
-
The name of an annotation to use.
Return values
mixed —The definitoin from the plugin.
getPrivateMethod()
Gets a private or protected method from a class using reflection.
public
static getPrivateMethod(object|string $class, string $methodName) : ReflectionMethod
Parameters
- $class : object|string
-
The class instance or the name of the class.
- $methodName : string
-
The name of the method to get.
Return values
ReflectionMethod —The method instance.
getPrivateProperty()
Gets a private or protected property from a class using reflection.
public
static getPrivateProperty(object|string $class, string $propertyName[, bool $returnReflectionProperty = FALSE ]) : mixed
Parameters
- $class : object|string
-
The class instance or the name of the class.
- $propertyName : string
-
The name of the property to get.
- $returnReflectionProperty : bool = FALSE
-
Flag to return a ReflectionProperty object instead of value.
Return values
mixed —The property value.
getRandomGenerator()
Gets the random generator for the utility methods.
public
static getRandomGenerator() : mixed
Tags
getServiceInfoFromClass()
Gets information about service from YAML file.
public
static getServiceInfoFromClass(string $serviceClass) : array<string|int, mixed>|null
Parameters
- $serviceClass : string
-
A class to search.
Return values
array<string|int, mixed>|null —An array with information, or NULL if nothing found.
getStringTranslationStub()
Returns a stub translation manager that just returns the passed string.
public
static getStringTranslationStub() : mixed
Tags
initEntityTypeManagerStubs()
Initializes the main services to work with entities stubs.
public
static initEntityTypeManagerStubs() : void
Initializes a bundle of services, required to work with entity stubs:
- entity_type.manager
- language_manager
- entity_field.manager
- entity.query.sql
- string_translation
- plugin.manager.field.field_type
- typed_data_manager
- uuid Also adds them to the Drupal Container.
initService()
Initializes a service from the service name or class.
public
static initService(string $serviceNameOrClass[, string $serviceNameToCheck = NULL ][, array<string|int, mixed>|null $mockMethods = NULL ][, string|null $overrideClass = NULL ]) : object
The function tries to auto detect the service YAML file location automatically by service name or class name. If auto magic doesn't work for your case, use the initServiceFromYaml() directly.
Parameters
- $serviceNameOrClass : string
-
The name of the service id in YAML file of the current module, or the full name of a service class.
- $serviceNameToCheck : string = NULL
-
A service name to check matching the declared one in services.yml file. Acts only if the class name is passed as a first argument.
- $mockMethods : array<string|int, mixed>|null = NULL
-
A list of method to mock when creating the instance.
- $overrideClass : string|null = NULL
-
A class to override the default service class.
Return values
object —The initialized class instance.
initServiceFromYaml()
Initializes a service from YAML file with passing services as arguments.
public
static initServiceFromYaml(string|array<string|int, mixed> $servicesYamlFileOrData, string $name[, array<string|int, mixed>|null $mockMethods = NULL ][, string|null $overrideClass = NULL ]) : object
Parameters
- $servicesYamlFileOrData : string|array<string|int, mixed>
-
The path to the YAML file, or an array with data from YAML.
- $name : string
-
The name of the service.
- $mockMethods : array<string|int, mixed>|null = NULL
-
A list of method to mock when creating the instance.
- $overrideClass : string|null = NULL
-
A class to override the default service class.
Return values
object —The initialized class instance.
isNestedArraySubsetOf()
Performs a check if the actial array is a subset of expected.
public
static isNestedArraySubsetOf(mixed $array, mixed $subset[, bool $throwErrors = FALSE ]) : bool
Parameters
- $array : mixed
-
The array to check. Returns false if passed variable is not an array.
- $subset : mixed
-
The array with values to check the subset.
- $throwErrors : bool = FALSE
-
Enables throwing notice errors when matching fails, with the explanation what exactly doesn't match.
Return values
bool —True if the array is the subset, false if not.
loadParametersFromYamlFile()
Load params from YAML file to the current service container.
public
static loadParametersFromYamlFile(string $file[, bool $override = TRUE ]) : void
Parameters
- $file : string
-
A path to a YAML file.
- $override : bool = TRUE
-
A flag to override the current parameters.
matchConditions()
Performs matching of passed conditions with the query.
public
static matchConditions(ConditionInterface|ConditionInterface $conditionsObject, ConditionInterface|ConditionInterface $conditionsExpectedObject[, bool|null $onlyListed = NULL ][, bool|null $throwErrors = FALSE ]) : bool
Parameters
- $conditionsObject : ConditionInterface|ConditionInterface
-
The query object to check.
- $conditionsExpectedObject : ConditionInterface|ConditionInterface
-
The query object with expected conditions.
- $onlyListed : bool|null = NULL
-
Forces to return false, if the checking query object contains more conditions than in object with expected conditions.
- $throwErrors : bool|null = FALSE
-
Enables throwing notice errors when matching fails, with the explanation what exactly doesn't match.
Return values
bool —True if is subset, false if not.
matchEntityCondition()
Matches a EntityQuery conditon to entity.
public
static matchEntityCondition(EntityInterface $entity, array<string|int, mixed> $condition) : bool
Parameters
- $entity : EntityInterface
-
The entity to use.
- $condition : array<string|int, mixed>
-
The condition to check.
Return values
bool —True if matches, false if not.
mockPhpFunction()
Sets a mock for a PHP build-in function for the namespace of a class.
public
static mockPhpFunction(string $name, string $class[, callable|null $callback = NULL ]) : MockedFunctionCalls
Warning! The function will be mocked for all classes in the passed class namespace, and will stay for all other test function in the file. So, always use TestHelpers::unmockPhpFunction() at the end of each test.
For your tests you call it in tearDownAfterClass() to always revert all mocks after finishing the current unit test, to not affect next tests.
Parameters
- $name : string
-
The function name.
- $class : string
-
The full class name (FQCN) to get the namespace.
- $callback : callable|null = NULL
-
A callback function to call, or NULL if no callback is needed.
Return values
MockedFunctionCalls —A MockedFunctionCalls object, containing list of all function calls.
queryIsSubsetOf()
Performs matching of passed conditions with the query.
public
static queryIsSubsetOf(ConditionInterface|ConditionInterface $query, ConditionInterface|ConditionInterface $queryExpected[, bool $onlyListed = FALSE ][, bool $throwErrors = TRUE ]) : bool
Parameters
- $query : ConditionInterface|ConditionInterface
-
The query object to check.
- $queryExpected : ConditionInterface|ConditionInterface
-
The query object with expected conditions.
- $onlyListed : bool = FALSE
-
Forces to return false, if the checking query object contains more conditions than in object with expected conditions.
- $throwErrors : bool = TRUE
-
Enables throwing notice errors when matching fails, with the explanation what exactly doesn't match.
Return values
bool —True if is subset, false if not.
saveEntity()
Creates a stub entity for an entity type from a given class and saves it.
public
static saveEntity(string $entityTypeNameOrClass[, array<string|int, mixed> $values = NULL ][, array<string|int, mixed> $translations = NULL ][, array<string|int, mixed> $options = NULL ]) : EntityStubInterface|EntityInterface|MockObject
Parameters
- $entityTypeNameOrClass : string
-
A full path to an entity type class, or an entity type id for Drupal Core entities like
node
,taxonomy_term
, etc. - $values : array<string|int, mixed> = NULL
-
A list of values to set in the created entity.
- $translations : array<string|int, mixed> = NULL
-
A list of translations to add to the created entity.
- $options : array<string|int, mixed> = NULL
-
A list of options to entity stub creation:
- mockMethods: list of methods to make mockable.
- addMethods: list of additional methods.
- skipPrePostSave: a flag to use direct save on the storage without calling preSave and postSave functions. Can be useful if that functions have dependencies which hard to mock. Applies only on the first initialization of this node type.
- skipEntityConstructor: a flag to skip calling the entity constructor.
- fields: a list of custom field options by field name.
Applies only on the first initialization of this field.
Supportable formats:
- A string, indicating field type, like 'integer', 'string', 'entity_reference', only core field types are supported.
- An array with field configuration: type, settings, etc, like this: [ 'type' => 'entity_reference', 'settings' => ['target_type' => 'node'] 'translatable' => TRUE, 'required' => FALSE, 'cardinality' => 3, ].
- A field definition object, that will be applied to the field.
Return values
EntityStubInterface|EntityInterface|MockObject —The stub object for the entity.
service()
Gets the service stub or mock, or initiates a new one if missing.
public
static service(string $serviceName[, object|string|null $class = NULL ][, bool $forceOverride = NULL ][, array<string|int, mixed> $mockMethods = NULL ][, array<string|int, mixed> $addMockableMethods = NULL ][, bool $initService = NULL ][, string $servicesYamlFile = NULL ]) : object
Parameters
- $serviceName : string
-
The service name.
- $class : object|string|null = NULL
-
The class to use in service, allowed different types:
- object: attachs the initialized object to the service.
- string: creates a mock of the class by passed name.
- null: use stub from Test Heleprs of default class from Drupal Core.
- $forceOverride : bool = NULL
-
Control overriding the service:
- FALSE on NULL: overrides only if the class names are different.
- TRUE: always overrides the class by a new instance.
- $mockMethods : array<string|int, mixed> = NULL
-
The list of exist methods to make mokable.
- $addMockableMethods : array<string|int, mixed> = NULL
-
The list of new methods to make them mokable.
- $initService : bool = NULL
-
Initializes core service with constructor and passing all dependencies.
- $servicesYamlFile : string = NULL
-
A path to the services.yaml file when it can't be properly autodetected.
Return values
object —The initialised service object.
setMockedClassMethod()
Sets a closure function to a class method.
public
static setMockedClassMethod(object $class, string $method, Closure $closure) : void
This makes private class methods accessible inside the function via $this.
Parameters
- $class : object
-
The mocked class.
- $method : string
-
The method name.
- $closure : Closure
-
The closure function to bind.
setPrivateProperty()
Sets a private or protected property value in a class using reflection.
public
static setPrivateProperty(object|string $class, string $propertyName, mixed $value) : void
Parameters
- $class : object|string
-
The class instance or the name of the class.
- $propertyName : string
-
The name of the property to get.
- $value : mixed
-
The value to set.
setServices()
Initializes list of services and adds them to the container.
public
static setServices(array<string|int, mixed> $services[, bool $clearContainer = NULL ][, bool $forceOverride = NULL ][, bool $initServices = NULL ]) : void
Parameters
- $services : array<string|int, mixed>
-
An array with services, supports two formats:
- A numeric array with service names: adds default classes.
- An associative array with service name as a key and object or NULL in value: Attaches the passed class to the service, if NULL - creates a stub for default Drupal Core class.
- $clearContainer : bool = NULL
-
Clears the Drupal container, if TRUE.
- $forceOverride : bool = NULL
-
Control overriding the service:
- FALSE on NULL: overrides only if the class names are different.
- TRUE: always overrides the class by a new instance.
- $initServices : bool = NULL
-
Initializes core service with constructor and passing all dependencies.
unmockAllPhpFunctions()
Unmocks all functions, that was mocked by mockPhpFunction().
public
static unmockAllPhpFunctions() : mixed
unmockPhpFunction()
Unmocks the previously mocked PHP build-in function in a namespace.
public
static unmockPhpFunction(string $name, string $class) : mixed
Parameters
- $name : string
-
The function name.
- $class : string
-
The full class name (FQCN) to get the namespace.