Localisation updates from https://translatewiki.net.
[mediawiki.git] / tests / phpunit / mocks / MockServiceDependenciesTrait.php
blob629a5fcc63298fd6a16457365506150fc52d7d61
1 <?php
3 namespace MediaWiki\Tests\Unit;
5 use ReflectionClass;
6 use ReflectionParameter;
8 /**
9 * Helper trait for instantiating MW service object for testing
10 * with mocked dependencies.
13 trait MockServiceDependenciesTrait {
15 /**
16 * Construct a new instance of $serviceClass with all constructor arguments
17 * mocked. $parameterOverrides allows to provide some constructor argument.
19 * @param string $serviceClass
20 * @param array $parameterOverrides [ argument name => argument value ]
21 * @return mixed
23 protected function newServiceInstance(
24 string $serviceClass,
25 array $parameterOverrides
26 ) {
27 $params = [];
28 $reflectionClass = new ReflectionClass( $serviceClass );
29 $constructor = $reflectionClass->getConstructor();
30 foreach ( $constructor->getParameters() as $parameter ) {
31 $params[] = array_key_exists( $parameter->getName(), $parameterOverrides )
32 ? $parameterOverrides[$parameter->getName()]
33 : $this->getMockValueForParam( $parameter );
35 return new $serviceClass( ...$params );
38 /**
39 * Override if this doesn't produce suitable values for one or more of the parameters to your
40 * factory constructor or create method.
42 * @param ReflectionParameter $param One of the factory constructor's arguments
43 * @return mixed A value to pass that will allow the object to be constructed successfully
45 private function getMockValueForParam( ReflectionParameter $param ) {
46 $pos = $param->getPosition();
47 $type = $param->getType();
48 if ( !$type || $type->getName() === 'string' ) {
49 // Optimistically assume a string is okay
50 return "some unlikely string $pos";
52 $type = $type->getName();
53 if ( $type === 'array' || $type === 'iterable' ) {
54 return [ "some unlikely string $pos" ];
57 if ( class_exists( $type ) || interface_exists( $type ) ) {
58 return $this->createMock( $type );
61 $this->fail( "Unrecognized parameter type $type" );