Skip to content

Commit 9ee825d

Browse files
committed
Merge branch '4.4'
* 4.4: [PhpUnitBridge] Add docs for ClassExistsMock
2 parents fe6005e + e6f81ff commit 9ee825d

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
@@ -589,6 +589,78 @@ conditions::
589589
],
590590
]);
591591

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

0 commit comments

Comments
 (0)