{"id":23209053,"url":"https://github.com/olvlvl/phpunit-given","last_synced_at":"2026-01-27T03:31:24.825Z","repository":{"id":65701990,"uuid":"597258059","full_name":"olvlvl/phpunit-given","owner":"olvlvl","description":"An alternative to PHPUnit's ReturnValueMap and ReturnCallback. A convenient solution to migrate from Prophecy.","archived":false,"fork":false,"pushed_at":"2024-11-02T02:31:03.000Z","size":19,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-16T17:45:35.897Z","etag":null,"topics":["php","phpunit","test-doubles"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/olvlvl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2023-02-04T01:38:29.000Z","updated_at":"2024-11-02T02:18:36.000Z","dependencies_parsed_at":"2023-02-19T00:15:48.539Z","dependency_job_id":null,"html_url":"https://github.com/olvlvl/phpunit-given","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olvlvl%2Fphpunit-given","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olvlvl%2Fphpunit-given/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olvlvl%2Fphpunit-given/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olvlvl%2Fphpunit-given/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/olvlvl","download_url":"https://codeload.github.com/olvlvl/phpunit-given/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230175926,"owners_count":18185088,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["php","phpunit","test-doubles"],"created_at":"2024-12-18T18:13:58.043Z","updated_at":"2026-01-27T03:31:19.807Z","avatar_url":"https://github.com/olvlvl.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# olvlvl/phpunit-given\n\n[![Packagist](https://img.shields.io/packagist/v/olvlvl/phpunit-given.svg)](https://packagist.org/packages/olvlvl/phpunit-given)\n[![Code Coverage](https://img.shields.io/coveralls/olvlvl/phpunit-given.svg)](https://coveralls.io/r/olvlvl/phpunit-given)\n[![Downloads](https://img.shields.io/packagist/dt/olvlvl/phpunit-given.svg)](https://packagist.org/packages/olvlvl/phpunit-given)\n\n_olvlvl/phpunit-given_ provides an alternative to [PHPUnit](https://phpunit.de/)'s [ReturnValueMap][] and [ReturnCallback][], as well as a convenient solution to migrate from [Prophecy][].\n\n#### Disclaimer\n\nIn most cases `ReturnCallback` with `match` can be used effectively. Don't use this package if you're comfortable with these and don't need extra features.\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewillReturnCallback(fn (Integer $int) =\u003e match (true) {\n    $int \u003c new Integer(6) =\u003e 'too small',\n    $int \u003e new Integer(9) =\u003e 'too big',\n    default =\u003e 'just right';\n}));\n```\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewill($this\n    -\u003egiven(Assert::lessThan(new Integer(6)))-\u003ereturn('too small')\n    -\u003egiven(Assert::greaterThan(new Integer(9)))-\u003ereturn('too big')\n    -\u003edefault()-\u003ereturn('just right')\n);\n```\n\n#### Usage\n\nThis is a simple example, more [use cases](#use-cases) below.\n\n```php\nuse olvlvl\\Given\\GivenTrait;\nuse PHPUnit\\Framework\\TestCase;\n\nfinal class IntegerNameTest extends TestCase\n{\n    use GivenTrait; // \u003c-- adds the method 'given'\n\n    public function testName(): void\n    {\n        $mock = $this-\u003ecreateMock(IntegerName::class);\n        $mock-\u003emethod('name')-\u003ewill($this\n            -\u003egiven(new Integer(6))-\u003ereturn(\"six\")\n            -\u003egiven(new Integer(12))-\u003ereturn(\"twelve\")\n            -\u003edefault()-\u003ethrow(LogicException::class)\n        );\n\n        $this-\u003eassertEquals(\"six\", $mock-\u003ename(new Integer(6)));\n        $this-\u003eassertEquals(\"twelve\", $mock-\u003ename(new Integer(12)));\n\n        $this-\u003eexpectException(LogicException::class);\n        $mock-\u003ename(new Integer(99));\n    }\n}\n```\n\n\n\n#### Installation\n\n```bash\ncomposer require olvlvl/phpunit-given\n```\n\n\n\n## Motivation\n\nComing from [Prophecy][], [C# Moq](), [Golang Mock](https://github.com/golang/mock), or [Kotlin Mockk](https://mockk.io/), one would expect at least one of the following examples to work, but they do not.\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock\n    -\u003emethod('name')\n    -\u003ewith(new Integer(6))\n    -\u003ewillReturn(\"six\");\n$mock\n    -\u003emethod('name')\n    -\u003ewith(new Integer(12))\n    -\u003ewillReturn(\"twelve\");\n\n// the next line crashes with: Expectation failed\n$this-\u003eassertEquals(\"six\", $mock-\u003ename(new Integer(6)));\n```\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock\n    -\u003emethod('name')\n    -\u003ewith(new Integer(6))-\u003ewillReturn(\"six\");\n    // the next line crashes with: Method parameters already configured\n    -\u003ewith(new Integer(12))-\u003ewillReturn(\"twelve\");\n\n$this-\u003eassertEquals(\"six\", $mock-\u003ename(new Integer(6)));\n```\n\nTo return a value given certain arguments, one is expected to use [ReturnValueMap][] or [ReturnCallback][]. `ReturnValueMap` seems simple enough, but because it looks for [exact matches](https://github.com/sebastianbergmann/phpunit/blob/39efa00da7afd8460975f8532eb2687288472c27/src/Framework/MockObject/Stub/ReturnValueMap.php#L40) it fails when objects are included in the arguments, unless they are the same instances. Besides, `ReturnValueMap` does not support constraints, you can forget doing anything fancy with it. That leaves us with `ReturnCallback`, which can be used effectively with `match` but requires the introduction of logic in the test, [a practice that is discouraged](https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices#avoid-logic-in-tests).\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewillReturnCallback(fn (Integer $int) =\u003e match ($int) {\n    new Integer(6) =\u003e 'six',\n    new Integer(12) =\u003e 'twelve',\n    default =\u003e throw new Exception\n}));\n```\n\nMy motivation for creating _olvlvl/phpunit-given_, is to have an alternative to [ReturnValueMap][] and [ReturnCallback][], that looks similar to what we find in other testing frameworks, and that allows easy migration from [Prophecy][].\n\nSome PHPUnit issues, for reference:\n\n- [Feature similar to withConsecutive(), but without checking order](https://github.com/sebastianbergmann/phpunit/issues/4026)\n- [Improvements on withConsecutive with return](https://github.com/sebastianbergmann/phpunit/issues/4255)\n- [Remove withConsecutive()](https://github.com/sebastianbergmann/phpunit/issues/4565)\n- [Symphony: Remove occurrences of withConsecutive()](https://github.com/symfony/symfony/pull/49621/files)\n\n## Use cases\n\n### Comparing with objects\n\n[ReturnValueMap][] doesn't work with objects because it [uses strict equality when comparing\narguments](https://github.com/sebastianbergmann/phpunit/blob/39efa00da7afd8460975f8532eb2687288472c27/src/Framework/MockObject/Stub/ReturnValueMap.php#L40). The following code throws a `TypeError` exception because `ReturnValueMap` cannot find a match and defaults to a `null` value.\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewill($this-\u003ereturnValueMap([\n    [ new Integer(6), \"six\" ],\n    [ new Integer(12), \"twelve\" ],\n]));\n\n$mock-\u003ename(new Integer(6)); // throws TypeError\n```\n\n_olvlvl/phpunit-given_ substitutes values with `Assert::equalTo()` and compares arguments using constraints. Having objects in the arguments is not a problem.\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewill($this\n    -\u003egiven(new Integer(6))-\u003ereturn(\"six\")\n    -\u003egiven(new Integer(12))-\u003ereturn(\"twelve\")\n);\n\n$this-\u003eassertEquals(\"six\", $mock-\u003ename(new Integer(6)));\n$this-\u003eassertEquals(\"twelve\", $mock-\u003ename(new Integer(12)));\n```\n\n**Note:** You can use `Assert::identicalTo()` to check for the same instance.\n\n\n\n### Using constraints\n\nWe established that values are substituted with `Assert::equalTo()` internally. Instead of values, you can also use constraints:\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewill($this\n    -\u003egiven(Assert::lessThan(new Integer(6)))-\u003ereturn('too small')\n    -\u003egiven(Assert::greaterThan(new Integer(9)))-\u003ereturn('too big')\n    -\u003edefault()-\u003ereturn('just right')\n);\n\n$this-\u003eassertEquals(\"too small\", $mock-\u003ename(new Integer(5)));\n$this-\u003eassertEquals(\"too big\", $mock-\u003ename(new Integer(10)));\n$this-\u003eassertEquals(\"just right\", $mock-\u003ename(new Integer(6)));\n$this-\u003eassertEquals(\"just right\", $mock-\u003ename(new Integer(9)));\n```\n\n\n\n### Migrating from Prophecy\n\n_olvlvl/phpunit-given_ is a convenient solution to migrate from Prophecy because the code is quite similar:\n\n```php\n$container = $this-\u003eprophesize(ContainerInterface::class);\n$container-\u003ehas('serviceA')-\u003ewillReturn(true);\n$container-\u003ehas('serviceB')-\u003ewillReturn(false);\n```\n```php\n$container = $this-\u003ecreateMock(ContainerInterface::class);\n$container-\u003emethod('has')-\u003ewill($this\n    -\u003egiven('serviceA')-\u003ereturn(true)\n    -\u003egiven('serviceB')-\u003ereturn(false)\n);\n```\n\n`throw()` is an alternative to `willThrow()`, and you can mismatch `return()` and `throw()`:\n\n```php\n$container = $this-\u003eprophesize(ContainerInterface::class);\n$container-\u003eget('serviceA')-\u003ewillReturn($serviceA);\n$container-\u003eget('serviceB')-\u003ewillThrow(new LogicException());\n```\n```php\n$container = $this-\u003ecreateMock(ContainerInterface::class);\n$container-\u003emethod('get')-\u003ewill($this\n    -\u003egiven('serviceA')-\u003ereturn($serviceA)\n    -\u003egiven('serviceB')-\u003ethrow(LogicException::class)\n);\n```\n\nContrary to Prophecy, _olvlvl/phpunit-given_ does not return `null` by default, instead it throws an exception:\n\n```php\n$mock = $this-\u003ecreateMock(IntegerName::class);\n$mock-\u003emethod('name')-\u003ewill($this\n    -\u003egiven(new Integer(6))-\u003ereturn(\"six\")\n    -\u003egiven(new Integer(12))-\u003ereturn(\"twelve\")\n);\n\n$mock-\u003ename(new Integer(13)); // throws an exception\n```\n```text\nLogicException : Unexpected invocation: Test\\olvlvl\\Given\\Acme\\IntegerName::name(Test\\olvlvl\\Given\\Acme\\Integer Object (...)): string, didn't match any of the constraints: [ [ is equal to Test\\olvlvl\\Given\\Acme\\Integer Object \u0026000000000000000c0000000000000000 (\n'value' =\u003e 6\n) ], [ is equal to Test\\olvlvl\\Given\\Acme\\Integer Object \u002600000000000001af0000000000000000 (\n'value' =\u003e 12\n) ] ]\n```\n\n\n\n----------\n\n\n\n## Continuous Integration\n\nThe project is continuously tested by [GitHub actions](https://github.com/olvlvl/phpunit-given/actions).\n\n[![Tests](https://github.com/olvlvl/phpunit-given/actions/workflows/test.yml/badge.svg)](https://github.com/olvlvl/phpunit-given/actions/workflows/test.yml)\n[![Static Analysis](https://github.com/olvlvl/phpunit-given/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/olvlvl/phpunit-given/actions/workflows/static-analysis.yml)\n[![Code Style](https://github.com/olvlvl/phpunit-given/actions/workflows/code-style.yml/badge.svg)](https://github.com/olvlvl/phpunit-given/actions/workflows/code-style.yml)\n\n\n\n## Code of Conduct\n\nThis project adheres to a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in\nthis project and its community, you're expected to uphold this code.\n\n\n\n## Contributing\n\nSee [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n\n\n## License\n\n**olvlvl/phpunit-given** is released under the [BSD-3-Clause](LICENSE).\n\n\n\n[ReturnValueMap]: https://github.com/sebastianbergmann/phpunit/blob/39efa00da7afd8460975f8532eb2687288472c27/src/Framework/MockObject/Stub/ReturnValueMap.php\n[ReturnCallback]: https://github.com/sebastianbergmann/phpunit/blob/39efa00da7afd8460975f8532eb2687288472c27/src/Framework/MockObject/Stub/ReturnCallback.php\n[Prophecy]: https://github.com/phpspec/prophecy/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folvlvl%2Fphpunit-given","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Folvlvl%2Fphpunit-given","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folvlvl%2Fphpunit-given/lists"}