@@ -565,6 +565,78 @@ conditions::
565565 ],
566566 ]);
567567
568+ Class Existence Based Tests
569+ ---------------------------
570+
571+ Tests that behave differently depending on existing classes, for example Composer's
572+ development dependencies, are often hard to test for the alternate case. For that
573+ reason, this component also provides mocks for these PHP functions:
574+
575+ * :phpfunction: `class_exists `
576+ * :phpfunction: `interface_exists `
577+ * :phpfunction: `trait_exists `
578+
579+ Use Case
580+ ~~~~~~~~
581+
582+ Consider the following example that relies on the ``Vendor\DependencyClass `` to
583+ toggle a behavior::
584+
585+ use Vendor\DependencyClass;
586+
587+ class MyClass
588+ {
589+ public function hello(): string
590+ {
591+ if (class_exists(DependencyClass::class)) {
592+ return 'The dependency bahavior.';
593+ }
594+
595+ return 'The default behavior.';
596+ }
597+ }
598+
599+ A regular test case for ``MyClass `` (assuming the development dependencies
600+ are installed during tests) would look like::
601+
602+ use MyClass;
603+ use PHPUnit\Framework\TestCase;
604+
605+ class MyClassTest extends TestCase
606+ {
607+ public function testHello()
608+ {
609+ $class = new MyClass();
610+ $result = $class->hello(); // "The dependency bahavior."
611+
612+ // ...
613+ }
614+ }
615+
616+ In order to test the default behavior instead use the
617+ ``ClassExistsMock::withMockedClasses() `` to configure the expected
618+ classes, interfaces and/or traits for the code to run::
619+
620+ use MyClass;
621+ use PHPUnit\Framework\TestCase;
622+ use Vendor\DependencyClass;
623+
624+ class MyClassTest extends TestCase
625+ {
626+ // ...
627+
628+ public function testHelloDefault()
629+ {
630+ ClassExistsMock::register(MyClass::class);
631+ ClassExistsMock::withMockedClasses([DependencyClass::class => false]);
632+
633+ $class = new MyClass();
634+ $result = $class->hello(); // "The default bahavior."
635+
636+ // ...
637+ }
638+ }
639+
568640Troubleshooting
569641---------------
570642
0 commit comments