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
:
<?php declare(strict_types=1);
final class SomeClass
{
public function doSomething(Dependency $dependency): string
{
$result = '';
// ...
return $result . $dependency->doSomething();
}
}
<?php declare(strict_types=1);
interface Dependency
{
public function doSomething(): string;
}
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
:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class SomeClassTest extends TestCase
{
public function testDoesSomething(): void
{
$sut = new SomeClass;
// Create a test stub for the Dependency interface
$dependency = $this->createStub(Dependency::class);
// Configure the test stub
$dependency->method('doSomething')
->willReturn('foo');
$result = $sut->doSomething($dependency);
$this->assertStringEndsWith('foo', $result);
}
}
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:
<?php declare(strict_types=1);
class C
{
public function m(): D
{
// Do something.
}
}
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.
short hand |
longer syntax |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
:
<?php declare(strict_types=1);
interface X
{
public function m(): bool;
}
<?php declare(strict_types=1);
interface Y
{
public function n(): int;
}
And you have a class that you want to test named Z
:
<?php declare(strict_types=1);
final class Z
{
public function doSomething(X&Y $input): bool
{
$result = false;
// ...
return $result;
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class StubForIntersectionExampleTest extends TestCase
{
public function testCreateStubForIntersection(): void
{
$o = $this->createStubForIntersectionOfInterfaces([X::class, Y::class]);
// $o is of type X ...
$this->assertInstanceOf(X::class, $o);
// ... and $o is of type Y
$this->assertInstanceOf(Y::class, $o);
}
}
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()
:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ReturnArgumentExampleTest extends TestCase
{
public function testReturnArgumentStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Configure the stub.
$stub->method('doSomething')
->will($this->returnArgument(0));
// $stub->doSomething('foo') returns 'foo'
$this->assertSame('foo', $stub->doSomething('foo'));
// $stub->doSomething('bar') returns 'bar'
$this->assertSame('bar', $stub->doSomething('bar'));
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ReturnSelfExampleTest extends TestCase
{
public function testReturnSelf(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Configure the stub.
$stub->method('doSomething')
->will($this->returnSelf());
// $stub->doSomething() returns $stub
$this->assertSame($stub, $stub->doSomething());
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ReturnValueMapExampleTest extends TestCase
{
public function testReturnValueMapStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Create a map of arguments to return values.
$map = [
['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
];
// Configure the stub.
$stub->method('doSomething')
->will($this->returnValueMap($map));
// $stub->doSomething() returns different values depending on
// the provided arguments.
$this->assertSame('d', $stub->doSomething('a', 'b', 'c'));
$this->assertSame('h', $stub->doSomething('e', 'f', 'g'));
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ReturnCallbackExampleTest extends TestCase
{
public function testReturnCallbackStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Configure the stub.
$stub->method('doSomething')
->will($this->returnCallback('str_rot13'));
// $stub->doSomething($argument) returns str_rot13($argument)
$this->assertSame('fbzrguvat', $stub->doSomething('something'));
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class OnConsecutiveCallsExampleTest extends TestCase
{
public function testOnConsecutiveCallsStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Configure the stub.
$stub->method('doSomething')
->will($this->onConsecutiveCalls(2, 3, 5, 7));
// $stub->doSomething() returns a different value each time
$this->assertSame(2, $stub->doSomething());
$this->assertSame(3, $stub->doSomething());
$this->assertSame(5, $stub->doSomething());
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ThrowExceptionExampleTest extends TestCase
{
public function testThrowExceptionStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->createStub(SomeClass::class);
// Configure the stub.
$stub->method('doSomething')
->will($this->throwException(new Exception));
// $stub->doSomething() throws Exception
$stub->doSomething();
}
}
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):
<?php declare(strict_types=1);
final class Subject
{
private array $observers = [];
public function attach(Observer $observer): void
{
$this->observers[] = $observer;
}
public function doSomething(): void
{
// ...
$this->notify('something');
}
private function notify(string $argument): void
{
foreach ($this->observers as $observer) {
$observer->update($argument);
}
}
// ...
}
<?php declare(strict_types=1);
interface Observer
{
public function update(string $argument): void;
}
Here is an example that shows how to use a mock object to test the interaction between
Subject
and Observer
objects:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class SubjectTest extends TestCase
{
public function testObserversAreUpdated(): void
{
$observer = $this->createMock(Observer::class);
$observer->expects($this->once())
->method('update')
->with($this->identicalTo('something'));
$subject = new Subject;
$subject->attach($observer);
$subject->doSomething();
}
}
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 timesnever()
returns a matcher that matches when the method it is evaluated for is never executedatLeastOnce()
returns a matcher that matches when the method it is evaluated for is executed at least onceonce()
returns a matcher that matches when the method it is evaluated for is executed exactly onceexactly(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
:
<?php declare(strict_types=1);
interface X
{
public function m(): bool;
}
<?php declare(strict_types=1);
interface Y
{
public function n(): int;
}
And you have a class that you want to test named Z
:
<?php declare(strict_types=1);
final class Z
{
public function doSomething(X&Y $input): bool
{
$result = false;
// ...
return $result;
}
}
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:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class MockForIntersectionExampleTest extends TestCase
{
public function testCreateMockForIntersection(): void
{
$o = $this->createMockForIntersectionOfInterfaces([X::class, Y::class]);
// $o is of type X ...
$this->assertInstanceOf(X::class, $o);
// ... and $o is of type Y
$this->assertInstanceOf(Y::class, $o);
}
}
createConfiguredMock()
The createConfiguredMock()
method is a convenience wrapper around createMock()
that allows configuring
return values using an associative array (['methodName' => <return value>]
):
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class CreateConfiguredMockExampleTest extends TestCase
{
public function testCreateConfiguredMock(): void
{
$o = $this->createConfiguredMock(
SomeInterface::class,
[
'doSomething' => 'foo',
'doSomethingElse' => 'bar',
]
);
// $o->doSomething() now returns 'foo'
$this->assertSame('foo', $o->doSomething());
// $o->doSomethingElse() now returns 'bar'
$this->assertSame('bar', $o->doSomethingElse());
}
}
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.
<?php declare(strict_types=1);
abstract class AbstractClass
{
public function concreteMethod()
{
return $this->abstractMethod();
}
abstract public function abstractMethod();
}
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class AbstractClassTest extends TestCase
{
public function testConcreteMethod(): void
{
$stub = $this->getMockForAbstractClass(AbstractClass::class);
$stub->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($stub->concreteMethod());
}
}
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.
<?php declare(strict_types=1);
trait AbstractTrait
{
public function concreteMethod()
{
return $this->abstractMethod();
}
abstract public function abstractMethod();
}
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class AbstractTraitTest extends TestCase
{
public function testConcreteMethod(): void
{
$mock = $this->getMockForTrait(AbstractTrait::class);
$mock->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(true));
$this->assertTrue($mock->concreteMethod());
}
}
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
:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class WsdlStubExampleTest extends TestCase
{
public function testWebserviceCanBeStubbed(): void
{
$service = $this->getMockFromWsdl(__DIR__ . '/HelloService.wsdl');
$service->method('sayHello')
->willReturn('Hello');
$this->assertSame('Hello', $service->sayHello('message'));
}
}
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()
:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class MockBuilderExampleTest extends TestCase
{
public function testStub(): void
{
// Create a stub for the SomeClass class.
$stub = $this->getMockBuilder(SomeClass::class)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->getMock();
// Configure the stub.
$stub->method('doSomething')
->willReturn('foo');
// Calling $stub->doSomething() will now return
// 'foo'.
$this->assertSame('foo', $stub->doSomething());
}
}