Skip to main content

PHPUnit 13: Managing return values for parameter sets

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Recently, my good friend Sebastian Bergmann published an article about how to use an alternative implementation of withConsecutive() calls in PHPUnit 13.

This article was particularly helpful as I had just upgraded one of our projects to PHPUnit 13 and needed to test multiple method calls.

However, I found that the article lacked information on managing return values. After testing a few approaches without success, I reached out to Sebastian, who kindly pointed me to the relevant documentation. In return, I promised to write a quick blog post covering my findings.

The newly introduced withParameterSetsInOrder() method allows you to configure a mock object to accept multiple parameter sets. Here's an example:

$issuesMock = $this->createMock(Issues::class);
$issuesMock->expects($this->exactly(2))
->method('create')
->withParameterSetsInOrder(
[
$projectId,
$title,
$description,
],
[
$projectId2,
$title2,
$description2,
],
);

If the order of the parameter sets doesn't matter, you can use the withParameterSetsInAnyOrder() method instead.

To define the return values for each call, use the willReturn() method and list all returning values as separate parameters:

$issuesMock = $this->createMock(Issues::class);
$issuesMock->expects($this->exactly(2))
->method('create')
->withParameterSetsInOrder(
[
$projectId,
$title,
$description,
],
[
$projectId2,
$title2,
$description2,
],
)
->willReturn(
1,
2,
);

This will return the values 1 and 2 for the first and second calls to the mocked create() method, respectively.

In conclusion, the withParameterSetsInOrder() and willReturn() methods in PHPUnit 13 provide a convenient way to configure mock objects for multiple parameter sets and define return values for each call.