8000 minor #11903 [PhpUnitBridge] Add docs for ClassExistsMock (ro0NL) · symfony/symfony-docs@8ebb564 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8ebb564

Browse files
committed
minor #11903 [PhpUnitBridge] Add docs for ClassExistsMock (ro0NL)
This PR was squashed before being merged into the 4.3 branch (closes #11903). Discussion ---------- [PhpUnitBridge] Add docs for ClassExistsMock fixes #10528 Commits ------- 2534240 [PhpUnitBridge] Add docs for ClassExistsMock
2 parents 5a3d82d + 2534240 commit 8ebb564

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

components/phpunit_bridge.rst

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,78 @@ conditions::
593593
],
594594
]);
595595

596+
Class Existence Based Tests
597+
---------------------------
598+
599+
Tests that behave differently depending on existing classes, for example Composer's
600+
development dependencies, are often hard to test for the alternate case. For that
601+
reason, this component also provides mocks for these PHP functions:
602+
603+
* :phpfunction:`class_exists`
604+
* :phpfunction:`interface_exists`
605+
* :phpfunction:`trait_exists`
606+
607+
Use Case
608+
~~~~~~~~
609+
610+
Consider the following example that relies on the ``Vendor\DependencyClass`` to
611+
toggle a behavior::
612+
613+
use Vendor\DependencyClass;
614+
615+
class MyClass
616+
{
617+
public function hello(): string
618+
{
619+
if (class_exists(DependencyClass::class)) {
620+
return 'The dependency bahavior.';
621+
}
622+
623+
return 'The default behavior.';
624+
}
625+
}
626+
627+
A regular test case for ``MyClass`` (assuming the development dependencies
628+
are installed during tests) would look like::
629+
630+
use MyClass;
631+
use PHPUnit\Framework\TestCase;
632+
633+
class MyClassTest extends TestCase
634+
{
635+
public function testHello()
636+
{
637+
$class = new MyClass();
638+
$result = $class->hello(); // "The dependency bahavior."
639+
640+
// ...
641+
}
642+
}
643+
644+
In order to test the default behavior instead use the
645+
``ClassExistsMock::withMockedClasses()`` to configure the expected
646+
classes, interfaces and/or traits for the code to run::
647+
648+
use MyClass;
649+
use PHPUnit\Framework\TestCase;
650+
use Vendor\DependencyClass;
651+
652+
class MyClassTest extends TestCase
653+
{
654+
// ...
655+
656+
public function testHelloDefault()
657+
{
658+
ClassExistsMock::register(MyClass::class);
659+
ClassExistsMock::withMockedClasses([DependencyClass::class => false]);
660+
661+
$class = new MyClass();
662+
$result = $class->hello(); // "The default bahavior."
663+
664+
// ...
665+
}
666+
}
667+
596668
Troubleshooting
597669
---------------
598670

0 commit comments

Comments
 (0)
0