6. Test Doubles

Gerard Meszaros introduces the concept of Test Doubles in his “xUnit Test Patterns” book like so:

Sometimes it is just plain hard to test the system under test (SUT) because it depends on other components that cannot be used in the test environment. This could be because they aren’t available, they will not return the results needed for the test or because executing them would have undesirable side effects. In other cases, our test strategy requires us to have more control or visibility of the internal behavior of the SUT.

When we are writing a test in which we cannot (or chose not to) use a real depended-on component (DOC), we can replace it with a Test Double. The Test Double doesn’t have to behave exactly like the real DOC; it merely has to provide the same API as the real one so that the SUT thinks it is the real one!

The createStub(string $type) and createMock(string $type) methods can be used in a test to automatically generate an object that can act as a test double for the specified original type (interface or class name). This test double object can be used in every context where an object of the original type is expected or required.

Limitation: final, private, and static methods

Please note that final, private, and static methods cannot be doubled. They are ignored by PHPUnit’s test double functionality and retain their original behavior except for static methods which will be replaced by a method throwing an exception.

Limitation: Enumerations and readonly classes

Enumerations (enum) are final classes and therefore cannot be doubled. readonly classes cannot be extended by classes that are not readonly and therefore cannot be doubled.

Favour doubling interfaces over doubling classes

Not only because of the limitations mentioned above, but also to improve your software design, favour the doubling of interfaces over the doubling of classes.

Test Stubs

The practice of replacing an object with a test double that (optionally) returns configured return values is referred to as stubbing. You can use a test stub to “replace a real component on which the SUT depends so that the test has a control point for the indirect inputs of the SUT. This allows the test to force the SUT down paths it might not otherwise execute” (Gerard Meszaros).

createStub()

createStub(string $type) returns a test stub for the specified type. The creation of this test stub is performed using best practice defaults: the __construct() and __clone() methods of the original class are not executed and the arguments passed to a method of the test double will not be cloned.

If these defaults are not what you need then you can use the getMockBuilder(string $type) method to customize the test double generation using a fluent interface.

By default, all methods of the original class are replaced with an implementation that returns an automatically generated value that satisfies the method’s return type declaration (without calling the original method).

willReturn()

Using the willReturn() method, for instance, you can configure these implementations to return a specified value when called. This configured value must be compatible with the method’s return type declaration.

Consider that we have a class that we want to test, SomeClass, which depends on Dependency:

Example 6.1 The class we want to test

  1. <?php declare(strict_types=1);
  2. final class SomeClass
  3. {
  4. public function doSomething(Dependency $dependency): string
  5. {
  6. $result = '';
  7. // ...
  8. return $result . $dependency->doSomething();
  9. }
  10. }

Example 6.2 The dependency we want to stub

  1. <?php declare(strict_types=1);
  2. interface Dependency
  3. {
  4. public function doSomething(): string;
  5. }

Here is a first example of how to use the createStub(string $type) method to create a test stub for Dependency so that we can test SomeClass without using a real implementation of Dependency:

Example 6.3 Stubbing a method call to return a fixed value

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class SomeClassTest extends TestCase
  4. {
  5. public function testDoesSomething(): void
  6. {
  7. $sut = new SomeClass;
  8. // Create a test stub for the Dependency interface
  9. $dependency = $this->createStub(Dependency::class);
  10. // Configure the test stub
  11. $dependency->method('doSomething')
  12. ->willReturn('foo');
  13. $result = $sut->doSomething($dependency);
  14. $this->assertStringEndsWith('foo', $result);
  15. }
  16. }

Limitation: Methods named “method”

The example shown above only works when the original interface or class does not declare a method named “method”.

If the original interface or class does declare a method named “method” then $stub->expects($this->any())->method('doSomething')->willReturn('foo'); has to be used.

In the example shown above, we first use the createStub() method to create a test stub, an object that looks like an instance of Dependency.

We then use the Fluent Interface that PHPUnit provides to specify the behavior for the test stub.

“Behind the scenes”, PHPUnit automatically generates a new PHP class that implements the desired behavior when the createStub() method is used.

Please note that createStub() will automatically and recursively stub return values based on a method’s return type. Consider the example shown below:

Example 6.4 A method with a return type declaration

  1. <?php declare(strict_types=1);
  2. class C
  3. {
  4. public function m(): D
  5. {
  6. // Do something.
  7. }
  8. }

In the example shown above, the C::m() method has a return type declaration indicating that this method returns an object of type D. When a test double for C is created and no return value is configured for m() using willReturn() (see above), for instance, then when m() is invoked PHPUnit will automatically create a test double for D to be returned.

Similarly, if m had a return type declaration for a scalar type then a return value such as 0 (for int), 0.0 (for float), or [] (for array) would be generated.

So far, we have configured simple return values using willReturn($value). This is a shorthand syntax provided for convenience. Table 6.1 shows the available stubbing shorthands alongside their longer counterparts.

Table 6.1 Stubbing shorthands

short hand

longer syntax

willReturn($value)

will($this->returnValue($value))

willReturnArgument($argumentIndex)

will($this->returnArgument($argumentIndex))

willReturnCallback($callback)

will($this->returnCallback($callback))

willReturnMap($valueMap)

will($this->returnValueMap($valueMap))

willReturnOnConsecutiveCalls($value1, $value2)

will($this->onConsecutiveCalls($value1, $value2))

willReturnSelf()

will($this->returnSelf())

willThrowException($exception)

will($this->throwException($exception))

We can use variations on this longer syntax to achieve more complex stubbing behaviour.

createStubForIntersectionOfInterfaces()

The createStubForIntersectionOfInterfaces(array $interface) method can be used to create a test stub for an intersection of interfaces based on a list of interface names.

Consider you have the following interfaces X and Y:

Example 6.5 An interface named X

  1. <?php declare(strict_types=1);
  2. interface X
  3. {
  4. public function m(): bool;
  5. }

Example 6.6 An interface named Y

  1. <?php declare(strict_types=1);
  2. interface Y
  3. {
  4. public function n(): int;
  5. }

And you have a class that you want to test named Z:

Example 6.7 A class named Z

  1. <?php declare(strict_types=1);
  2. final class Z
  3. {
  4. public function doSomething(X&Y $input): bool
  5. {
  6. $result = false;
  7. // ...
  8. return $result;
  9. }
  10. }

To test Z, we need an object that satisfies the intersection type X&Y. We can use the createStubForIntersectionOfInterfaces(array $interface) method to create a test stub that satisfies X&Y like so:

Example 6.8 Using createStubForIntersectionOfInterfaces() to create a test stub for an intersection type

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class StubForIntersectionExampleTest extends TestCase
  4. {
  5. public function testCreateStubForIntersection(): void
  6. {
  7. $o = $this->createStubForIntersectionOfInterfaces([X::class, Y::class]);
  8. // $o is of type X ...
  9. $this->assertInstanceOf(X::class, $o);
  10. // ... and $o is of type Y
  11. $this->assertInstanceOf(Y::class, $o);
  12. }
  13. }

returnArgument()

Sometimes you want to return one of the arguments of a method call (unchanged) as the result of a stubbed method call. Here is an example that shows how you can achieve this using returnArgument() instead of returnValue():

Example 6.9 Using returnArgument() to stub a method call to return one of the arguments

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class ReturnArgumentExampleTest extends TestCase
  4. {
  5. public function testReturnArgumentStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Configure the stub.
  10. $stub->method('doSomething')
  11. ->will($this->returnArgument(0));
  12. // $stub->doSomething('foo') returns 'foo'
  13. $this->assertSame('foo', $stub->doSomething('foo'));
  14. // $stub->doSomething('bar') returns 'bar'
  15. $this->assertSame('bar', $stub->doSomething('bar'));
  16. }
  17. }

returnSelf()

When testing a fluent interface, it is sometimes useful to have a stubbed method return a reference to the stubbed object. Here is an example that shows how you can use returnSelf() to achieve this:

Example 6.10 Using returnSelf() to stub a method call to return a reference to the stub object

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class ReturnSelfExampleTest extends TestCase
  4. {
  5. public function testReturnSelf(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Configure the stub.
  10. $stub->method('doSomething')
  11. ->will($this->returnSelf());
  12. // $stub->doSomething() returns $stub
  13. $this->assertSame($stub, $stub->doSomething());
  14. }
  15. }

returnValueMap()

Sometimes a stubbed method should return different values depending on a predefined list of arguments. Here is an example that shows how to use returnValueMap() to create a map that associates arguments with corresponding return values:

Example 6.11 Using returnValueMap() to stub a method call to return the value from a map

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class ReturnValueMapExampleTest extends TestCase
  4. {
  5. public function testReturnValueMapStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Create a map of arguments to return values.
  10. $map = [
  11. ['a', 'b', 'c', 'd'],
  12. ['e', 'f', 'g', 'h'],
  13. ];
  14. // Configure the stub.
  15. $stub->method('doSomething')
  16. ->will($this->returnValueMap($map));
  17. // $stub->doSomething() returns different values depending on
  18. // the provided arguments.
  19. $this->assertSame('d', $stub->doSomething('a', 'b', 'c'));
  20. $this->assertSame('h', $stub->doSomething('e', 'f', 'g'));
  21. }
  22. }

returnCallback()

When the stubbed method call should return a calculated value instead of a fixed one (see returnValue()) or an (unchanged) argument (see returnArgument()), you can use returnCallback() to have the stubbed method return the result of a callback function or method. Here is an example:

Example 6.12 Using returnCallback() to stub a method call to return a value from a callback

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class ReturnCallbackExampleTest extends TestCase
  4. {
  5. public function testReturnCallbackStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Configure the stub.
  10. $stub->method('doSomething')
  11. ->will($this->returnCallback('str_rot13'));
  12. // $stub->doSomething($argument) returns str_rot13($argument)
  13. $this->assertSame('fbzrguvat', $stub->doSomething('something'));
  14. }
  15. }

onConsecutiveCalls()

A simpler alternative to setting up a callback method may be to specify a list of desired return values. You can do this with the onConsecutiveCalls() method. Here is an example:

Example 6.13 Using onConsecutiveCalls() to stub a method call to return a list of values in the specified order

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class OnConsecutiveCallsExampleTest extends TestCase
  4. {
  5. public function testOnConsecutiveCallsStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Configure the stub.
  10. $stub->method('doSomething')
  11. ->will($this->onConsecutiveCalls(2, 3, 5, 7));
  12. // $stub->doSomething() returns a different value each time
  13. $this->assertSame(2, $stub->doSomething());
  14. $this->assertSame(3, $stub->doSomething());
  15. $this->assertSame(5, $stub->doSomething());
  16. }
  17. }

throwException()

Instead of returning a value, a stubbed method can also raise an exception. Here is an example that shows how to use throwException() to do this:

Example 6.14 Using throwException() to stub a method call to throw an exception

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class ThrowExceptionExampleTest extends TestCase
  4. {
  5. public function testThrowExceptionStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->createStub(SomeClass::class);
  9. // Configure the stub.
  10. $stub->method('doSomething')
  11. ->will($this->throwException(new Exception));
  12. // $stub->doSomething() throws Exception
  13. $stub->doSomething();
  14. }
  15. }

Mock Objects

The practice of replacing an object with a test double that verifies expectations, for instance asserting that a method has been called, is referred to as mocking.

You can use a mock object “as an observation point that is used to verify the indirect outputs of the SUT as it is exercised. Typically, the mock object also includes the functionality of a test stub in that it must return values to the SUT if it hasn’t already failed the tests but the emphasis is on the verification of the indirect outputs. Therefore, a mock object is a lot more than just a test stub plus assertions; it is used in a fundamentally different way” (Gerard Meszaros).

createMock()

createMock(string $type) returns a mock object for the specified type. The creation of this mock object is performed using best practice defaults: the __construct() and __clone() methods of the original class are not executed and the arguments passed to a method of the test double will not be cloned.

If these defaults are not what you need then you can use the getMockBuilder(string $type) method to customize the test double generation using a fluent interface.

By default, all methods of the original class are replaced with an implementation that returns an automatically generated value that satisfies the method’s return type declaration (without calling the original method). Furthermore, expectations for invocations of these methods (“method must be called with specified arguments”, “method must not be called”, …) can be configured.

Here is an example: suppose we want to test that the correct method, update() in our example, is called on an object that observes another object.

Here is the code for the Subject class and the Observer interface that are part of the System under Test (SUT):

Example 6.15 Subject class that is part of the System under Test (SUT)

  1. <?php declare(strict_types=1);
  2. final class Subject
  3. {
  4. private array $observers = [];
  5. public function attach(Observer $observer): void
  6. {
  7. $this->observers[] = $observer;
  8. }
  9. public function doSomething(): void
  10. {
  11. // ...
  12. $this->notify('something');
  13. }
  14. private function notify(string $argument): void
  15. {
  16. foreach ($this->observers as $observer) {
  17. $observer->update($argument);
  18. }
  19. }
  20. // ...
  21. }

Example 6.16 Observer interface that is part of the System under Test (SUT)

  1. <?php declare(strict_types=1);
  2. interface Observer
  3. {
  4. public function update(string $argument): void;
  5. }

Here is an example that shows how to use a mock object to test the interaction between Subject and Observer objects:

Example 6.17 Testing that a method gets called once and with a specified argument

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class SubjectTest extends TestCase
  4. {
  5. public function testObserversAreUpdated(): void
  6. {
  7. $observer = $this->createMock(Observer::class);
  8. $observer->expects($this->once())
  9. ->method('update')
  10. ->with($this->identicalTo('something'));
  11. $subject = new Subject;
  12. $subject->attach($observer);
  13. $subject->doSomething();
  14. }
  15. }

We first use the createMock() method to create a mock object for the Observer.

Because we are interested in verifying the communication between two objects (that a method is called and which arguments it is called with), we use the expects() and with() methods to specify what this communication should look like.

The with() method can take any number of arguments, corresponding to the number of arguments to the method being mocked. You can specify more advanced constraints on the method’s arguments than a simple match.

Constraints shows the constraints that can be applied to method arguments and here is a list of the matchers that are available to specify the number of invocations:

  • any() returns a matcher that matches when the method it is evaluated for is executed zero or more times

  • never() returns a matcher that matches when the method it is evaluated for is never executed

  • atLeastOnce() returns a matcher that matches when the method it is evaluated for is executed at least once

  • once() returns a matcher that matches when the method it is evaluated for is executed exactly once

  • exactly(int $count) returns a matcher that matches when the method it is evaluated for is executed exactly $count times

createMockForIntersectionOfInterfaces()

The createMockForIntersectionOfInterfaces(array $interface) method can be used to create a mock object for an intersection of interfaces based on a list of interface names.

Consider you have the following interfaces X and Y:

Example 6.18 An interface named X

  1. <?php declare(strict_types=1);
  2. interface X
  3. {
  4. public function m(): bool;
  5. }

Example 6.19 An interface named Y

  1. <?php declare(strict_types=1);
  2. interface Y
  3. {
  4. public function n(): int;
  5. }

And you have a class that you want to test named Z:

Example 6.20 A class named Z

  1. <?php declare(strict_types=1);
  2. final class Z
  3. {
  4. public function doSomething(X&Y $input): bool
  5. {
  6. $result = false;
  7. // ...
  8. return $result;
  9. }
  10. }

To test Z, we need an object that satisfies the intersection type X&Y. We can use the createMockForIntersectionOfInterfaces(array $interface) method to create a test stub that satisfies X&Y like so:

Example 6.21 Using createMockForIntersectionOfInterfaces() to create a mock object for an intersection type

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class MockForIntersectionExampleTest extends TestCase
  4. {
  5. public function testCreateMockForIntersection(): void
  6. {
  7. $o = $this->createMockForIntersectionOfInterfaces([X::class, Y::class]);
  8. // $o is of type X ...
  9. $this->assertInstanceOf(X::class, $o);
  10. // ... and $o is of type Y
  11. $this->assertInstanceOf(Y::class, $o);
  12. }
  13. }

createConfiguredMock()

The createConfiguredMock() method is a convenience wrapper around createMock() that allows configuring return values using an associative array (['methodName' => <return value>]):

Example 6.22 Using createConfiguredMock() to create a mock object and configure return values

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class CreateConfiguredMockExampleTest extends TestCase
  4. {
  5. public function testCreateConfiguredMock(): void
  6. {
  7. $o = $this->createConfiguredMock(
  8. SomeInterface::class,
  9. [
  10. 'doSomething' => 'foo',
  11. 'doSomethingElse' => 'bar',
  12. ]
  13. );
  14. // $o->doSomething() now returns 'foo'
  15. $this->assertSame('foo', $o->doSomething());
  16. // $o->doSomethingElse() now returns 'bar'
  17. $this->assertSame('bar', $o->doSomethingElse());
  18. }
  19. }

Abstract Classes and Traits

getMockForAbstractClass()

The getMockForAbstractClass() method returns a mock object for an abstract class. All abstract methods of the given abstract class are mocked. This allows for testing the concrete methods of an abstract class.

Example 6.23 An abstract class with a concrete method

  1. <?php declare(strict_types=1);
  2. abstract class AbstractClass
  3. {
  4. public function concreteMethod()
  5. {
  6. return $this->abstractMethod();
  7. }
  8. abstract public function abstractMethod();
  9. }

Example 6.24 A test for a concrete method of an abstract class

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class AbstractClassTest extends TestCase
  4. {
  5. public function testConcreteMethod(): void
  6. {
  7. $stub = $this->getMockForAbstractClass(AbstractClass::class);
  8. $stub->expects($this->any())
  9. ->method('abstractMethod')
  10. ->will($this->returnValue(true));
  11. $this->assertTrue($stub->concreteMethod());
  12. }
  13. }

getMockForTrait()

The getMockForTrait() method returns a mock object that uses a specified trait. All abstract methods of the given trait are mocked. This allows for testing the concrete methods of a trait.

Example 6.25 A trait with an abstract method

  1. <?php declare(strict_types=1);
  2. trait AbstractTrait
  3. {
  4. public function concreteMethod()
  5. {
  6. return $this->abstractMethod();
  7. }
  8. abstract public function abstractMethod();
  9. }

Example 6.26 A test for a concrete method of a trait

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class AbstractTraitTest extends TestCase
  4. {
  5. public function testConcreteMethod(): void
  6. {
  7. $mock = $this->getMockForTrait(AbstractTrait::class);
  8. $mock->expects($this->any())
  9. ->method('abstractMethod')
  10. ->will($this->returnValue(true));
  11. $this->assertTrue($mock->concreteMethod());
  12. }
  13. }

Web Services

When your application interacts with a web service you want to test it without actually interacting with the web service. To create stubs and mocks of web services, the getMockFromWsdl() method can be used.

This method returns a test stub based on a web service description in WSDL whereas createStub(), for instance, returns a test stub based on an interface or on a class.

Here is an example that shows how to stub the web service described in HelloService.wsdl:

Example 6.27 Stubbing a web service

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class WsdlStubExampleTest extends TestCase
  4. {
  5. public function testWebserviceCanBeStubbed(): void
  6. {
  7. $service = $this->getMockFromWsdl(__DIR__ . '/HelloService.wsdl');
  8. $service->method('sayHello')
  9. ->willReturn('Hello');
  10. $this->assertSame('Hello', $service->sayHello('message'));
  11. }
  12. }

MockBuilder API

As mentioned before, when the defaults used by the createStub() and createMock() methods to generate the test double do not match your needs then you can use the getMockBuilder($type) method to customize the test double generation using a fluent interface. Here is a list of methods provided by the Mock Builder:

  • onlyMethods(array $methods) can be called on the Mock Builder object to specify the methods that are to be replaced with a configurable test double. The behavior of the other methods is not changed. Each method must exist in the given mock class.

  • addMethods(array $methods) can be called on the Mock Builder object to specify the methods that don’t exist (yet) in the given mock class. The behavior of the other methods remains the same.

  • setConstructorArgs(array $args) can be called to provide a parameter array that is passed to the original class’ constructor (which is not replaced with a dummy implementation by default).

  • setMockClassName($name) can be used to specify a class name for the generated test double class.

  • disableOriginalConstructor() can be used to disable the call to the original class’ constructor.

  • enableOriginalConstructor() can be used to enable the call to the original class’ constructor.

  • disableOriginalClone() can be used to disable the call to the original class’ clone constructor.

  • enableOriginalClone() can be used to enable the call to the original class’ clone constructor.

  • disableAutoload() can be used to disable __autoload() during the generation of the test double class.

  • enableAutoload() can be used to enable __autoload() during the generation of the test double class.

  • disableArgumentCloning() can be used to disable the cloning of arguments passed to mocked methods.

  • enableArgumentCloning() can be used to enable the cloning of arguments passed to mocked methods.

  • enableProxyingToOriginalMethods() can be used to enable the invocation of the original methods.

  • disableProxyingToOriginalMethods() can be used to disable the invocation of the original methods.

  • setProxyTarget() can be used to set the proxy target for the invocation of the original methods.

  • allowMockingUnknownTypes() can be used to allow the doubling of unknown types.

  • disallowMockingUnknownTypes() can be used to disallow the doubling of unknown types.

  • enableAutoReturnValueGeneration() can be used to enable the automatic generation of return values when no return value is configured.

  • disableAutoReturnValueGeneration() can be used to disable the automatic generation of return values when no return value is configured.

Here is an example that shows how to use the Mock Builder’s fluent interface to configure the creation of a test stub. The configuration of this test double uses the same best practice defaults used by createStub() and createMock():

Example 6.28 Using the Mock Builder API to configure how the test double class is generated

  1. <?php declare(strict_types=1);
  2. use PHPUnit\Framework\TestCase;
  3. final class MockBuilderExampleTest extends TestCase
  4. {
  5. public function testStub(): void
  6. {
  7. // Create a stub for the SomeClass class.
  8. $stub = $this->getMockBuilder(SomeClass::class)
  9. ->disableOriginalConstructor()
  10. ->disableOriginalClone()
  11. ->disableArgumentCloning()
  12. ->disallowMockingUnknownTypes()
  13. ->getMock();
  14. // Configure the stub.
  15. $stub->method('doSomething')
  16. ->willReturn('foo');
  17. // Calling $stub->doSomething() will now return
  18. // 'foo'.
  19. $this->assertSame('foo', $stub->doSomething());
  20. }
  21. }