Summer Sale! All accounts are 50% off this week.

vincent15000's avatar

Mocking a class that is not injected

Hello,

I'm using PHPUnit for testing my applications.

Mocking is new to me (I use it for a few weeks) and I still have a lot to discover.

I have noticed that mocking works only for classes that are injected into another class as a dependency and it's necessary that the mocked class has been declared in the AppServiceProvider.

Is it specific to Laravel ? Or is it the same for PHPUnit in a vanilla PHP application ?

Thanks to help me better understand mocking.

V

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@vincent15000 In both vanilla PHP and Laravel, mocking works by substituting real objects with test mocking.

But in Laravel, the Service Container and Service Providers play an important role in resolving dependencies.

In vanilla PHP, you manually handle dependency injection, so mocking relies on your ability to control how dependencies are passed into the class.

Here is an example for vanilla PHP:

class Foo {
    protected $dependency;

    public function __construct(Dependency $dependency) {
        $this->dependency = $dependency;
    }

    public function doSomething() {
        return $this->dependency->performAction();
    }
}

// PHPUnit Test
class FooTest extends TestCase {
    public function testDoSomething() {
        $mockDependency = $this->createMock(Dependency::class);
        $mockDependency->method('performAction')->willReturn('mocked result');
        
        $foo = new Foo($mockDependency);

        $this->assertEquals('mocked result', $foo->doSomething());
    }
}
2 likes

Please or to participate in this conversation.